官方文檔說明
- 所有的 prop 都使得其父子 prop 之間形成了一個 單向下行綁定
- 父級 prop 的更新會向下流動到子組件中,但是反過來則不行
- 2.3.0+ 新增
.sync修飾符 - 以
update:my-prop-name的模式觸發事件實現 上行綁定 最終實現 雙向綁定
舉個栗子this.$emit('update:title', newTitle)
代碼實現
child.vue
<template>
<div>
<input type="text" v-model="sonValue">
<div>{{ fatherValue }}</div>
</div>
</template>
<script>
export default {
props: {
fatherValue: {
required: true
}
},
data () {
return {
sonValue: this.fatherValue
}
},
watch: {
sonValue (newValue, oldvalue) {
this.$emit('update:fatherValue', newValue)
},
fatherValue (newValue) {
this.sonValue = newValue
}
}
}
</script>
father.vue
<template> <div class="hello"> <!-- input實時改變value的值, 並且會實時改變child里的內容 --> <input type="text" v-model="value"> <child :fatherValue.sync="value" ></child> </div> </template> <script> import Child from './Child' //引入Child子組件 export default { data() { return { value: '' } }, components: { 'child': Child } } </script>
