什么是組件
按照慣例,引用Vue官網的一句話:
組件 (Component) 是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝可重用的代碼。在較高層面上,組件是自定義元素,Vue.js 的編譯器為它添加特殊功能。在有些情況下,組件也可以是原生 HTML 元素的形式,以 is 特性擴展。
組件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>
局部注冊:
var Child = { template: '<div>A custom component!</div>'}new Vue({ // ... components: { // <my-component> 將只在父模板可用 'my-component': Child }})DOM模板解析說明
組件在某些HTML標簽下會受到一些限制。
比如一下代碼,在table標簽下,組件是無效的。
<table> <my-row>...</my-row></table>
解決方法是,通過is屬性使用組件
<table> <tr is="my-row"></tr></table>
應當注意,如果您使用來自以下來源之一的字符串模板,將不會受限
<script type="text/x-template">
JavaScript 內聯模版字符串
.vue 組件
data使用函數,避免多組件互相影響
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'})如上,div下有三個組件,每個組件共享一個counter。當任意一個組件被點擊,所有組件的counter都會加一。
解決辦法如下
js
Vue.component('simple-counter', { template: '<button v-on:click="counter += 1">{{ counter }}</button>', data: function () { return {counter:0} }})new Vue({ el: '#example-2'})這樣每個組件生成后,都會有自己獨享的counter。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。
新聞熱點
疑難解答
圖片精選