v-model的原理詳解
v-model的本質(zhì)就是一個語法糖,實際上就是 :value="msg"
與 @input="msg = $event.target.value"
的簡寫。:value="msg"
從數(shù)據(jù)單向綁定到input框,當data數(shù)據(jù)中的msg內(nèi)容一旦改變,而input框數(shù)據(jù)也隨之改變。@input="msg = $event.target.value"
是為input框綁定了input事件,內(nèi)容改變則觸發(fā),而在觸發(fā)時又把這個input框的value值賦值給了data數(shù)據(jù)中的msg。
原本使用porps和$emit實現(xiàn)的父子組件通信。
這下面的代碼就實現(xiàn)了父子組件屬性的雙向綁定。
而這其中父組件中的子標簽屬性 :value="msg" @input="sendMsg"
是與 使用 v-model:"msg"
等價的,因為sendMsg(value){ console.log(value) this.msg = value }
方法的內(nèi)容是與v-model原理中的@input="msg = $event.target.value"
是一模一樣的意思,所以在父組件中我們可以使用以下代碼來與子組件雙向綁定
<!-- 結構 -->
<template>
<div id="app">
<MyInput v-model="msg"></MyInput>
</div>
</template>
<!-- 行為 -->
<script>
import MyInput from './components/MyInput.vue';
export default {
name: "App",
data() {
return {
msg: "你好!vue",
};
},
components:{
MyInput
},
};
</script>
<!-- 樣式 -->
<style>
#app {
width: 100%;
height: 600px;
background-color: skyblue;
overflow: hidden;
}
</style>
而子組件則需要注意的是,使用 props:{ value:String },
來接受父組件數(shù)據(jù),必須是vaule:
<template>
<input type="text" :value="value"
@input="fun($event.target.value)">
</template>
<script>
export default {
props:{
value:String
},
methods:{
fun(e){
this.$emit('input',e)
}
}
}
</script>
.sync修飾符
使用v-model有一個壞處就是,子組件接收數(shù)據(jù)的鍵只可以使用value props:{ value:String }
,而這個修飾符.sync
就可以解決這個問題。
子組件中將修改觸發(fā)方法。文章來源:http://www.zghlxwxcb.cn/news/detail-694400.html
<template>
<input type="text" :value="msg"
@input="fun($event.target.value)">
</template>
<script>
export default {
props:{
msg:String
},
methods:{
fun(e){
//修改點update:要修改的屬性名稱
this.$emit('update:msg',e)
}
}
}
</script>
父組件中的修改點:文章來源地址http://www.zghlxwxcb.cn/news/detail-694400.html
<!-- 結構 -->
<template>
<div id="app">
<!-- 只需修改為 :傳遞數(shù)據(jù)名.sync="傳遞數(shù)據(jù)名" -->
<MyInput :msg.sync = "msg"></MyInput>
</div>
</template>
<!-- 行為 -->
<script>
import MyInput from './components/MyInput.vue';
export default {
name: "App",
data() {
return {
msg: "你好!vue",
};
},
components:{
MyInput
},
};
</script>
<!-- 樣式 -->
<style>
#app {
width: 100%;
height: 600px;
background-color: skyblue;
overflow: hidden;
}
</style>
到了這里,關于【vue2第十一章】v-model的原理詳解 與 如何使用v-model對父子組件的value綁定 和修飾符.sync的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!