vue自定義組件分為局部組件和全局組件
全局組件
全局組件格式
template 是模板
props 是自定義組件用到的屬性 可以是對象也可以是數(shù)組
組件的名稱通常用 - 來連接,也可以像這個用大駝峰命名,但是在使用的時候,還是要使用 - 大小寫之間用 - 連接,大寫變成小寫
Vue.component('MyComponentName', { /* ... */ })
組件名稱
Vue.component('my-component-name', {
//模板
template:` html 標(biāo)簽 `,
//定義的屬性名稱 props可以是數(shù)組 也可以是對象
props:["title","value"]
props:{
title: {
type: String, //類型
required: false //可以為空
},
value: {
type: Number,
default:0, //默認(rèn)值為0
required: true //不能為空
}
}
})
局部組件
每個組件就是一個小型的Vue實例,它里面除了不能設(shè)置el選項,其他選項它都有。
局部組件在vue 實例中 components:{} 中創(chuàng)建 創(chuàng)造的規(guī)則跟全局創(chuàng)建時一樣的,
局部創(chuàng)建只能在當(dāng)前實例使用
在使用組件時,在組件行類 的屬性前面要加上:
創(chuàng)建一個局部組件
<z-counter :label="item.label" :count="item.count" v-for="(item, index) in list" :key="index" @synccount="synccount(index,$event)"></z-counter>
在 components 中定義一個組件為z-counter 的組件
label 是標(biāo)題 readonly 是只讀,不能寫入
在組件中,定義的組件的屬性props默認(rèn)情況下是不能夠修改的,這個時候,我在data 中定義一個中轉(zhuǎn)變量
在vue實例中 data 可以是對象,也可以是一個方法,
但是在組件中,data只能是一個方法data,由該方法返回一個對象
因為組件可能會使用很多次,如果data選項是對象的話,會導(dǎo)致多個組件使用了同一份數(shù)據(jù)。
new Vue({
el: '#app',
data: {
list:[
{
label:"衣服",
count:5
},
{
label:"褲子",
count:6
},
{
label:"襪子",
count:10
},
]
},
methods:{
synccount(index,e){
this.list[index].count=e
},
},
components: {
"z-counter": {
template:
`
<div class="counter">
<div class="label">{{label}}</div>
<div class="btns">
<button @click="mydata--" :disabled="mydata===mincount">-</button>
<input type="text" v-model="mydata" class="text" readonly>
<button @click="mydata++" :disabled="mydata===maxcount">+</button>
</div>
</div>
`,
// props 是只讀的不能修改
//prop 也可以是數(shù)組[屬性名]
props: {
label: {
type: String,
//允許為空
required: false,
},
count: {
type: Number,
//不可為空
required: true
},
maxcount:{
type:Number,
default:999
},
mincount:{
type:Number,
default:1
}
},
data() {
return {
mydata: this.count
}
},
watch:{
mydata(val){
this.$emit('synccount',val)
}
}
}
},
})
在組件中創(chuàng)建一個監(jiān)聽器,監(jiān)聽mydata的值,如果中值發(fā)生變化,用this.$emit把數(shù)據(jù)發(fā)送給前面,保證數(shù)據(jù)是同時跟新的
第一個參數(shù)是自定義方法名,第一個參數(shù)是傳回去的值
this.$emit()自定義一個synccount 方法,方法名隨意,
在組件z-counter中 用@synccount=""的格式寫個方法來接收數(shù)據(jù),如果需要接收多個參數(shù),和默認(rèn)參數(shù) 需要在方法的參數(shù)最后面加入$event
完整格式 ↑
@synccount="synccount(index,$event)"