Vue.sync修饰符与$emit,update:xxx详解

Vue .sync修饰符与$emit(update:xxx)

.sync修饰符的作用

在对一个 prop 进行“双向绑定,单向修改”的场景下,因为子组件不能直接修改父组件,sync在2.3版本引入,作为一个事件绑定语法糖,利用EventBus,当子组件触发事件时,父组件会响应事件并实现数据更新,避免了子组件直接修改父组件传过来的内容。

.sync修饰符之前的写法

父组件:

<parent :myMessage=“bar” @update:myMessage=“func”>

js定义函数:

func(val){
        this.bar = val;
}

子组件,事件触发函数:

func2(){
        this.$emit(‘update:myMessage',valc);
}

也就是说,父组件需要传一个绑定值(myMessage)同时需要设置一个更新触发函数(func)给子组件修改绑定值的时候调用。

使用.sync修饰符的写法

会简化上面的写法,父组件不需要定义更新触发函数。

父组件:

<comp :myMessage.sync="bar"></comp>

子组件:

this.$emit('update:myMessage',valc);

sync 修饰符与 $emit(update:xxx) ,驼峰法 和 - 写法的区别,使用.sync修饰符,即变量应该使用驼峰法:

    // this.$emit('update:father-num',100);  //无效
    this.$emit('update:fatherNum',100); //有效
    //......
    <father v-bind:father-num.sync="test"></father>

不适用 .sync 修饰符,变量应该使用 - ,即father-num

this.$emit('update:father-num',100);  //有效
//this.$emit('update:fatherNum',100); // 无效
//......
<father v-bind:father-num="test" v-on:update:father-num="test=$event" ></father>

但从实践中发现,用 .sync 修饰符,这两种写法都是有效的。

在vue之中,当父组件向子组件传递属性的时候,如下使用驼峰法

<cpn :cMives="movies"></cpn>

在子组件中props:[‘cMives’],是接收不到属性的,应该使用-来绑定属性,接收依旧使用驼峰法。

 <cpn :c-mives="movies"></cpn>

综上,绑定时候用 “-”,接收和使用的时候用驼峰法,如果真的无效,再试试上面所说的那种情况。

原文地址:https://wjw1014.blog.csdn.net/article/details/108979101