实践笔记——vue父子组件数据双向绑定

背景

Vue设计中props为单向数据流,即props数据在父组件进行修改,并流向子组件。而在子组件里只能对props数据进行读取,不能进行修改,否则会触发报错。

为了达到在子组件里修改props值的要求,需要通过以下2步来实现

1. 父组件使用子组件时给prop值(value)添加.sync修饰符

2. 子组件通过 this.$emit("update:value", this.valueText)修改prop值(value)的值

//child.js
export default {
    name: "child",
    props: {
        value: undefined, //使用.sync绑定
    },
    data() {
        return {
            valueText: '',
        };
    },
    methods: {
        change(selection) {
            this.$emit("update:value", this.valueText);
        },
    },
};

// father.js
<child :value.sync="text"></child>

猜你喜欢

转载自blog.csdn.net/baidu_38798835/article/details/109303808