關(guān)鍵詞:Vue2.0橄登,父子組件傳值舰攒,prop數(shù)據(jù)雙向綁定
在做vue項(xiàng)目的時(shí)候败富,發(fā)現(xiàn)一些問(wèn)題以前碰到過(guò),但是沒(méi)有及時(shí)總結(jié)出現(xiàn)的問(wèn)題及原因摩窃,導(dǎo)致重新花費(fèi)時(shí)間找答案兽叮,在此總結(jié)在學(xué)習(xí)vue的過(guò)程中出現(xiàn)的一些問(wèn)題,方便后續(xù)查看
- 1.父子組件傳數(shù)據(jù)出現(xiàn)以下錯(cuò)誤
props單向數(shù)據(jù)流動(dòng)猾愿,即只能由父組件改變prop狀態(tài)鹦聪,子組件不能改變父組件狀態(tài)
解決方法:實(shí)現(xiàn)組件數(shù)據(jù)雙向綁定
eg. 模態(tài)框顯示與關(guān)閉(Modal使用iview)
父組件
<div class="container">
<!-- modal -->
<modal :visible="showModal" @on-change="change"></modal>
</div>
data () {
return {
showModal: false
}
},
methods: {
//④外層調(diào)用組件方注冊(cè)變更方法,將組件內(nèi)的數(shù)據(jù)變更蒂秘,同步到組件外的數(shù)據(jù)狀態(tài)中
change (val) {
this.showModal = val
}
}
});
}
}
子組件
<Modal title="提示" v-model="InfoModal">
...
</Modal>
props: {
visible: {
type: Boolean,
default: false
}
},
data () {
InfoModal: this.visible //①創(chuàng)建props屬性visible的副本--InfoModal
},
methods: {
//③組件內(nèi)對(duì)InfoModal變更后向外部發(fā)送事件通知
handleChange (val) {
this.$emit('on-change', val)
}
},
// ②監(jiān)聽(tīng)外部對(duì)props屬性visible的變更泽本,并同步到組件內(nèi)的data屬性InfoModal中
},
watch: {
visible (val) {
this.InfoModal = val
}
}
Vue2.0中,實(shí)現(xiàn)組件屬性的雙向綁定方式
核心:組件內(nèi)部自己變了告訴外部姻僧,外部決定要不要變规丽。
步驟:
- 在組件內(nèi)的data對(duì)象中創(chuàng)建一個(gè)props屬性的副本
- 創(chuàng)建針對(duì)props屬性的watch來(lái)同步組件外對(duì)props的修改
- 創(chuàng)建針對(duì)props副本的watch蒲牧,通知到組件外(在組件內(nèi)向外層(父組件)發(fā)送通知,通知組件內(nèi)屬性變更赌莺,然后由外層(父組件)自己來(lái)變更他的數(shù)據(jù))
更多參考詳見(jiàn) http://www.jb51.net/article/98881.htm