美文网首页
Vue .sync修饰符与$emit(update:xxx)

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

作者: driver_ab | 来源:发表于2022-03-18 11:16 被阅读0次

.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 .sync修饰符与$emit(update:xxx)

      本文链接:https://www.haomeiwen.com/subject/bnyidrtx.html