vue component組件使用方法詳解
什么是組件
按照慣例,引用Vue官網(wǎng)的一句話:
組件 (Component) 是 Vue.js 最強(qiáng)大的功能之一。組件可以擴(kuò)展 HTML 元素,封裝可重用的代碼。在較高層面上,組件是自定義元素,Vue.js 的編譯器為它添加特殊功能。在有些情況下,組件也可以是原生 HTML 元素的形式,以 is 特性擴(kuò)展。
組件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標(biāo)簽下會受到一些限制。
比如一下代碼,在table標(biāo)簽下,組件是無效的。
<table> <my-row>...</my-row> </table>
解決方法是,通過is屬性使用組件
<table> <tr is="my-row"></tr> </table>
應(yīng)當(dāng)注意,如果您使用來自以下來源之一的字符串模板,將不會受限
<script type="text/x-template">
JavaScript 內(nèi)聯(lián)模版字符串
.vue 組件
data使用函數(shù),避免多組件互相影響
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。當(dāng)任意一個組件被點擊,所有組件的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'
})
這樣每個組件生成后,都會有自己獨(dú)享的counter。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
進(jìn)入Hooks時代寫出高質(zhì)量react及vue組件詳解
這篇文章主要介紹了Hooks時代中如何寫出高質(zhì)量的react和vue組件的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Vue3使用video-player實現(xiàn)視頻播放
video-player是一個基于video.js的視頻播放器組件,本文主要介紹了Vue3使用video-player實現(xiàn)視頻播放,具有一定的參考價值,感興趣的可以了解一下2024-01-01

