方式1:子组件发送emit,触发父组件修改
父组件
<template><div><son :count="count" @updateCount="updateCount" /></div>
</template><script>
import son from "./son";
export default {data() {return {count: 0,};},components: { son },methods: {updateCount(data) {this.count = data;},},
};
</script>
子组件
<template><div class="goodsBasic"><div>父组件:{{ count }}</div><el-button @click="changeCount">方式1</el-button></div>
</template>
<script>
export default {props: {count: {type: Number,default: 0,},},methods: {changeCount() {this.$emit("updateCount", this.count + 1);},},
};
</script>
方式2:在子组件那里强制修改
父组件
<template><div><son :text.sync="text" /></div>
</template><script>
import son from "./son";
export default {data() {return {text: "hello world",};},components: { son },
};
</script>
子组件
<template><div class="goodsBasic"><div>父组件:{{ text }}</div><el-button @click="changeCount">方式2</el-button></div>
</template>
<script>
export default {props: {text: {type: String,default: "",},},methods: {changeCount() {this.$emit("update:text", "我被强制修改了");},},
};
</script>
方式3:子组件定义一个值,来代替父组件传过来的值(不推荐,该方法父子组件的值不是同步修改)
父组件
<template><div><son :count="count" /></div>
</template><script>
import son from "./son";
export default {data() {return {count: 0,};},components: { son },
};
</script>
子组件
<template><div class="goodsBasic"><div>子组件:{{ son_count }}</div><el-button @click="changeCount">方式3</el-button></div>
</template>
<script>
export default {props: {count: {type: Number,default: 0,},},data() {return {son_count: this.count,};},methods: {changeCount() {this.son_count++;},},
};
</script>