vue設(shè)計(jì)模式是數(shù)據(jù)流在組件之間是單向流動(dòng),組件內(nèi)部是數(shù)據(jù)雙向綁定,
父組件一般會(huì)通過(guò)props綁定數(shù)據(jù)傳遞給子組件;
<parent-component? :props_data=props_data/>
子組件通過(guò)props接受父組件傳遞過(guò)來(lái)的值;
<child-component/>
export default{
name:'child-component',
props:['props_data']
data(){
return{
name:'小白'
}
}
}
props基本形式(不能傳遞對(duì)象,只改變了索引,數(shù)據(jù)會(huì)上下都改變,如果傳遞的是對(duì)象的話必須深拷貝,建議再計(jì)算屬性computed改變)
props設(shè)置類型和默認(rèn)值
props:{
propA: {
? ? ? type: Number,
? ? ? default: 100,//默認(rèn)值是100;
? ? },
propB: {
? ? ? type: String,
? ? ? required: true//是否必須傳遞;
? ? },
}
在組件中直接使用this.propA
父子組件之間方法相互調(diào)用
子組件調(diào)用父組件的方法
<parent-component @set_data=set_data/>父組件中定義子組件中調(diào)用的方法,方法名可以不一樣,
<child-component/>
export default{
name:'child-component',
data(){
return{
name:'小白'
}
},
methods:{
onclick(){
this.$emit('set_data',params)//父組件接受子組件的的傳遞參數(shù)
}
},
}
父元素調(diào)用子組件的方法
<child-component ref='childModel'/>
methods:{
onclick(){
this.ref['childModel'].$emit('child_mothod',params)
}
}
這種寫(xiě)的話在子組件生命周期中監(jiān)聽(tīng)就可以了
mounted(){
this.$on('child_mothod',(params)=>{
console.log('調(diào)用方法后傳遞的參數(shù)',params)
})
}
methods:{
onclick(){
this.ref['childModel'].child_mothod(params)
}
}
這樣寫(xiě)的話在子組件直接方法中直接接受就可以了
methods:{
child_mothod(params){
console.log('父組件傳遞的參數(shù)',params)
}
}