vue component組件使用方法詳解
什么是組件
按照慣例,引用Vue官網(wǎng)的一句話:
組件 (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 內(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。當任意一個組件被點擊,所有組件的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。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vscode+vue cli3.0創(chuàng)建項目配置Prettier+eslint方式
這篇文章主要介紹了vscode+vue cli3.0創(chuàng)建項目配置Prettier+eslint方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
ant design vue動態(tài)循環(huán)生成表單以及自定義校驗規(guī)則詳解
這篇文章主要介紹了ant design vue動態(tài)循環(huán)生成表單以及自定義校驗規(guī)則詳解,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
Vuepress生成文檔部署到gitee.io的注意事項及說明
這篇文章主要介紹了Vuepress生成文檔部署到gitee.io的注意事項及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
vue3.0使用vue-pdf-embed在線預覽pdf 控制頁碼顯示范圍不生效問題解決
這篇文章主要介紹了vue3.0使用vue-pdf-embed在線預覽pdf 控制頁碼顯示范圍不生效問題的問題及解決方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-01-01

