vue自定義組件實(shí)現(xiàn)雙向綁定
場景:
我們比較常用的父子組件之間的交互方式:父組件通過props將數(shù)據(jù)流入到子組件;子組件通過$emit將更新后的數(shù)組發(fā)送的父組件;
今天,我們通過另一種方式實(shí)現(xiàn)交互,參考input框的v-model,實(shí)現(xiàn)自定義組件的雙向數(shù)據(jù)綁定。即:父組件值改變,子組件的值跟著改變;反之,子組件值發(fā)生變化,父組件值隨之變化
子組件定義:
由于不能直接修改props屬性值,我們這里定義valueData,通過監(jiān)聽實(shí)時(shí)接收value值,通過click方法修改valueData。這里注意model語法糖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>
父組件定義:
父組件通過v-model綁定text值,名稱不一定是value,可以是其他任意符合命名規(guī)范的字符串,這里是text。子組件通過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)目測試。無論是通過父組件改變值,還是子組件改變值。兩個組件通過v-mode綁定的值始終保持一致。
答疑:
有同學(xué)就問了 ,這不是和通過props向下流入數(shù)據(jù),再通過$emit方式向上傳遞數(shù)據(jù)一樣么也能實(shí)現(xiàn)我這種雙向綁定的效果。 其實(shí)不然,如果不通過v-model,那么我們勢必會在父組件寫這樣的代碼:
<test-children @change='changeText'></test-children>
然后在通過定義changeText方法修改text值。
試想,當(dāng)我們的頁面比較復(fù)雜,引用組件量比較龐大,頁面中就需要多定義這樣十幾、二十幾個方法。可閱讀行大大降低,增加了維護(hù)成本。
擴(kuò)展:
vue2.3之后提供了sync方式,也能實(shí)現(xiàn)雙向綁定
父組件中的寫法:
<test-children :value.sync='text'></test-children>
子組件中不需要使用下面model定義,直接刪除即可。
model: {prop: “value”,event: “change”},
向父組件傳遞數(shù)據(jù)使用如下方式:
this.$emit('update:value', this.valueData);
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)2. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案3. HTML5 Canvas繪制圖形從入門到精通4. 讀大數(shù)據(jù)量的XML文件的讀取問題5. css代碼優(yōu)化的12個技巧6. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲7. asp批量添加修改刪除操作示例代碼8. PHP循環(huán)與分支知識點(diǎn)梳理9. ASP.NET MVC使用異步Action的方法10. ASP實(shí)現(xiàn)加法驗(yàn)證碼
