How to use components in vue.js: 1. Extend HTML elements and encapsulate reusable code; 2. Components are custom elements, and the compiler of [Vue.js] adds special functions to it; 3. , components can also be in the form of native HTML elements, extended with the is attribute.
【Recommended related articles: vue.js】
How to use component in vue.js:
What is a component
According to convention, quote A sentence from the Vue official website:
Component is one of the most powerful features of Vue.js. Components can extend HTML elements, encapsulating reusable code. At a high level, a component is a custom element to which Vue.js's compiler adds special functionality. In some cases, components can also take the form of native HTML elements, extended with the is attribute.
Registration of component component
Global component:
Vue.component('todo-item',{ props:['grocery'], template:'<li>{{grocery.text}}</li>' }) var app7 = new Vue({ el:"#app7", data:{ groceryList:[ {"id":0,"text":"蔬菜"}, {"id":1,"text":"奶酪"}, {"id":2,"text":"其他"} ] } })
<div id="app7"> <ol> <todo-item v-for="grocery in groceryList" v-bind:grocery="grocery" v-bind:key="grocery.id"> </todo-item> </ol> </div>
Local registration:
var Child = { template: '<div>A custom component!</div>' } new Vue({ // ... components: { // <my-component> 将只在父模板可用 'my-component': Child } })
DOM template parsing instructions
Components will be subject to some restrictions under certain HTML tags.
For example, in the code, under the table tag, the component is invalid.
<table> <my-row>...</my-row> </table>
The workaround is to use the component via the is attribute
<table> <tr is="my-row"></tr> </table>
It should be noted that if you use a string template from one of the following sources, it will not be restricted
<script type="text/x-template">
JavaScript inline template string
.vue
Component
data uses functions to avoid multiple components affecting each other
html
<div id="example-2"> <simple-counter></simple-counter> <simple-counter></simple-counter> <simple-counter></simple-counter> </div>
js
var data = { counter: 0 } Vue.component('simple-counter', { template: '<button v-on:click="counter += 1">{{ counter }}</button>', data: function () { return data } }) new Vue({ el: '#example-2' })
As above, there are three components under the div, and each component shares a counter. When any component is clicked, the counters of all components will be incremented by one.
The solution is as follows
js
Vue.component('simple-counter', { template: '<button v-on:click="counter += 1">{{ counter }}</button>', data: function () { return {counter:0} } }) new Vue({ el: '#example-2' })
In this way, after each component is generated, it will have its own exclusive counter.
Related free learning recommendations: JavaScript (video)
The above is the detailed content of How to use component in vue.js. For more information, please follow other related articles on the PHP Chinese website!