Vue 自定義組件v-model父子組件傳值雙向綁定
之前自己寫過一個自定義組件,父組件使用 v-model 進行雙向數據綁定的,寫了好幾次,當時明白,但是過了幾天又忘了,寫一下吧。
日常我們使用v-model
<div id="app">
<p>{{message}}</p>
<input type="text" v-model='message'>
</div>
<script>
var vueApp = new Vue({
el:'#app',
data:{
message:"我其實是一個語法糖"
}
})
</script>
去除它的語法糖
<div id="app">
<p>{{message}}</p>
<input type="text" v-bind:value='message' @input='message = $event.target.value'>
</div>
<script>
var vueApp = new Vue({
el: '#app',
data: {
message: "我其實是一個語法糖"
}
})
</script>
自定義組件如何使用v-model
vue里面自定義組件v-model的語法糖:
<custom v-model='something'></custom>
約等於
<custom :value="something" @input="value => { something = value }"></custom>
用 v-model 語法糖來向父組件傳遞值。
父組件使用v-model與子組件表單實現—雙向綁定。
在子組件里面,首先在props里面接收一下value值,然后初始化到newValue里面,然后監聽newValue值變化,變化后發射事件到父組件
watch:{
newValue(){
this.$emit('input', this.newValue)
}
}
還有一篇:https://blog.csdn.net/weixin_42776111/article/details/108979101
