Creating a Basic Reactive Counter
Show how to create a reactive counter that increments when a button is clicked using Vue.js 3's Composition API.
<div id="app">
<h1>{{ counter }}</h1>
<button @click="increment">Increment</button>
</div>
This is the HTML structure with Vue.js directives. It includes a container div with an id of 'app'. Inside, there is an 'h1' element for displaying the counter value which is reactive and updates automatically bindings '{{ counter }}'. A button element is also included, where the '@click' directive calls the 'increment' method defined in the Vue instance.
<script src="https://unpkg.com/vue@next"></script>
<script>
const { createApp, ref } = Vue;
const App = {
setup() {
const counter = ref(0);
function increment() {
counter.value++;
}
return { counter, increment };
}
};
createApp(App).mount('#app');
</script>
This script includes a reference to the Vue.js 3 library and defines the Vue component using the Composition API. The 'createApp' and 'ref' functions from Vue are destructured. The 'counter' is a reactive reference to the value 0, and the 'increment' function increases the 'counter' value by one. Finally, the Vue app is mounted to the DOM element with id 'app'.
<style>
#app {
text-align: center;
margin-top: 50px;
}
h1 {
font-size: 2em;
margin-bottom: 20px;
}
button {
font-size: 1em;
padding: 10px 20px;
}
</style>
The CSS styles for the application. The '#app' selector targets the main container, centers the text, and adds some margin at the top. The 'h1' selector defines the style of the counter display with a larger font size and some space below. The 'button' selector targets the increment button, providing it with styling in terms of size and padding for better presentation and user experience.