Vue .sync修饰符与$emit(update:xxx)写法问题

问题描述

最近在学习Vue,在学习自定义事件的.sync修饰符实现改变数值时发现一个问题如下
由于props的大小写命名:fatherNum,对应不同的$emit()会有不同的效果,具体如下
使用.sync修饰符,即

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


不使用.sync,即

      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>

我贴下具体代码吧,有点难说清楚,问题出现在$emit('update:xxx')xxx写法问题

相关代码

    Vue.component('father',{
        props:{
            'fatherNum':Number
        },
        template:`
        <div >
            <h1>fatherNum:{{fatherNum}}</h1>
            <button v-on:click="testFunction">father</button>
        </div>`,
        methods:{
            testFunction:function () {
                // this.$emit('update:father-num',100);  //.sync写法无效,无sync写法有效
                this.$emit('update:fatherNum',100); //.sync写法有效,无sync写法无效
        }
    }});
</script>
<div id="container">
    <p>.sync写法</p>
    <father v-bind:father-num.sync="test"></father>
    <p>无sync写法</p>
    <father v-bind:father-num="test" v-on:update:father-num="test=$event" ></father>
</div>
<script>
    var container = new Vue({
        el:"#container",
        data:{
            test:1
        }
    })
</script>

请大佬赐教

阅读 25.3k
1 个回答

我在这里,找到一篇可能有关的 解答文章:

v-bind的【.camel】 API — Vue.js

clipboard.png

v-bind指令:

.camel - (2.1.0+) 将 kebab-case 特性名转换为 camelCase. (从 2.1.0 开始支持)

不知道这个属性,是否会有作用?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题