vue自定義組件實(shí)現(xiàn)雙向綁定
場(chǎng)景:
我們比較常用的父子組件之間的交互方式:父組件通過(guò)props將數(shù)據(jù)流入到子組件;子組件通過(guò)$emit將更新后的數(shù)組發(fā)送的父組件;
今天,我們通過(guò)另一種方式實(shí)現(xiàn)交互,參考input框的v-model,實(shí)現(xiàn)自定義組件的雙向數(shù)據(jù)綁定。即:父組件值改變,子組件的值跟著改變;反之,子組件值發(fā)生變化,父組件值隨之變化
子組件定義:
由于不能直接修改props屬性值,我們這里定義valueData,通過(guò)監(jiān)聽(tīng)實(shí)時(shí)接收value值,通過(guò)click方法修改valueData。這里注意model語(yǔ)法糖prop 是接收的props屬性value,保持一致。event是先上傳遞的事件名。
代碼如下:
<template> <div> <div>{{ `子組件值: ${value}` }}</div> <div @click='click'>點(diǎn)擊此處修改值</div> </div></template><script>export default { name: '', model: { prop: 'value', event: 'change' }, props: { value: Number }, components: {}, data() { return { valueData: '' }; }, watch: { value(newValue, oldValue) { this.valueData = newValue; console.log(`子組件值:${newValue}`); } }, created() { }, mounted() { }, methods: { click() { this.valueData++; this.$emit('change', this.valueData); } }};</script><style lang=’less’ scoped></style>
父組件定義:
父組件通過(guò)v-model綁定text值,名稱(chēng)不一定是value,可以是其他任意符合命名規(guī)范的字符串,這里是text。子組件通過(guò)change事件更新數(shù)據(jù)后,v-mode綁定值隨之變化。或者父組件修改text值后,子組件value值隨之變化。
代碼如下:
<template> <div> <div>{{ `父組件值:${text}` }}</div> <div @click='click'>點(diǎn)擊此處修改值</div> <span>-----------------------------------------------------------</span> <test-children v-model='text'></test-children> </div></template><script>import TestChildren from '@/views/TestChildren';export default { name: '', components: { TestChildren }, data() { return { text: 1 }; }, created() { }, mounted() { }, watch: { text(newValue, oldValue) { console.log(`父組件值:${newValue}`); } }, methods: { click() { this.text--; } }};</script><style lang=’less’ scoped></style>
結(jié)果:
直接copy代碼到自己項(xiàng)目測(cè)試。無(wú)論是通過(guò)父組件改變值,還是子組件改變值。兩個(gè)組件通過(guò)v-mode綁定的值始終保持一致。
答疑:
有同學(xué)就問(wèn)了 ,這不是和通過(guò)props向下流入數(shù)據(jù),再通過(guò)$emit方式向上傳遞數(shù)據(jù)一樣么也能實(shí)現(xiàn)我這種雙向綁定的效果。 其實(shí)不然,如果不通過(guò)v-model,那么我們勢(shì)必會(huì)在父組件寫(xiě)這樣的代碼:
<test-children @change='changeText'></test-children>
然后在通過(guò)定義changeText方法修改text值。
試想,當(dāng)我們的頁(yè)面比較復(fù)雜,引用組件量比較龐大,頁(yè)面中就需要多定義這樣十幾、二十幾個(gè)方法。可閱讀行大大降低,增加了維護(hù)成本。
擴(kuò)展:
vue2.3之后提供了sync方式,也能實(shí)現(xiàn)雙向綁定
父組件中的寫(xiě)法:
<test-children :value.sync='text'></test-children>
子組件中不需要使用下面model定義,直接刪除即可。
model: {prop: “value”,event: “change”},
向父組件傳遞數(shù)據(jù)使用如下方式:
this.$emit('update:value', this.valueData);
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python 的 __str__ 和 __repr__ 方法對(duì)比2. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法3. Spring security 自定義過(guò)濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)4. IntelliJ IDEA設(shè)置背景圖片的方法步驟5. docker /var/lib/docker/aufs/mnt 目錄清理方法6. Python TestSuite生成測(cè)試報(bào)告過(guò)程解析7. 學(xué)python最電腦配置有要求么8. JAMon(Java Application Monitor)備忘記9. Python Scrapy多頁(yè)數(shù)據(jù)爬取實(shí)現(xiàn)過(guò)程解析10. Python OpenCV去除字母后面的雜線操作
