Component is a powerful Vue feature that allows extending basic HTML elements to encapsulate reusable code.
Components are one of the most powerful features of Vue. They help you extend basic HTML elements to encapsulate reusable code. At a high level, components are custom elements that Vue’s compiler attaches behavior to. In some cases, they may also appear as a native HTML element extended with the special is attribute.
Basic component
Javascript:
// First, we need a vue instance attached to a element
new Vue({ el: '#components-demo' })
// Then we define a new component called "button-counter"
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
// The template tag is where we write the component markup
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
HTML:
<div id="components-demo">
<button-counter></button-counter>
</div>
Vue will then compile the template to virtual DOM and its output will be rendered in the browser to the following:
<div id="components-demo">
<button>You clicked me 0 times.</button>
</div>
Then for each time you click the button, Vue will execute count++
resulting in count variable updating and triggering Vue re-render the component DOM to show the new value:
You have clicked me 1 times.