跳到主要内容
<!-- 父组件 -->
<template>
<div class="home">
<button @click="changeFood">改变food</button>
<p>{{ food }}</p>
<!-- 给子组件传值 -->
<test
:food="food"
@update:food="f => (food = f)"
/>
</div>
</template>

<script>
import Test from '@/components/Test.vue';
export default {
data() {
return {
food: '我是原来的值'
};
},
components: {
Test
},
methods: {
// 父组件改变 food
changeFood() {
this.food = '我是父组件改变的';
}
}
};
</script>
<!-- 子组件 -->
<template>
<div class="test">
<p>{{ innerFood }}</p>
<button @click="innerFood = '我是子组件改变的'">点击更改子组件</button>
</div>
</template>

<script>
export default {
data() {
return {
innerFood: this.food // 接收父组件传递过来的 food
};
},
props: {
food: String
},
watch: {
// 监听 父组件 food 变化
food(nv) {
this.innerFood = nv;
},
// 监听子组件innerFood变化,触发自定义方法,并将新值传递给父组件
innerFood(nv) {
this.$emit('update:food', nv);
}
}
};
</script>

优化:

<!-- 父组件 -->
<test :food="food" @update:food="f => (food = f)"></test>
<!-- ==> 注意:@update:food 必须是 @update:加上父组件中的该属性,否则无效 -->
<test :food.sync="food"></test>
<!-- 子组件,不再采用 data 接收, watch监听,在 emit,改为使用 computed 属性 -->
<script>
export default {
props: {
food: String
},
// 接收父组件传递过来的 food
computed: {
innerFood: {
get() {
return this.food;
},
set(nv) {
this.$emit('update:food', nv);
}
}
}
};
</script>