0
点赞
收藏
分享

微信扫一扫

查漏补缺-全面总结Vue3.0的新特性(10)v-model

前端王祖蓝 2022-03-12 阅读 63
前端vue3

在Vue2.x中,v-model相当于绑定value属性和input事件,它本质也是一个语法糖:

<child-component v-model="msg"></child-component>
<!-- 相当于 -->
<child-component :value="msg" @input="msg=$event"></child-component>

在某些情况下,我们需要对多个值进行双向绑定,其他的值就需要显示的使用回调函数来改变了:

<child-component 
    v-model="msg" 
    :msg1="msg1" 
    @change1="msg1=$event"
    :msg2="msg2" 
    @change2="msg2=$event">
</child-component>

在vue2.3.0+版本引入了.sync修饰符,其本质也是语法糖,是在组件上绑定@update:propName回调,语法更简洁:

<child-component 
    :msg1.sync="msg1" 
    :msg2.sync="msg2">
</child-component>

<!-- 相当于 -->

<child-component 
    :msg1="msg1" 
    @update:msg1="msg1=$event"
    :msg2="msg2"
    @update:msg2="msg2=$event">
</child-component>

Vue3中将v-model.sync进行了功能的整合,抛弃了.sync,表示:多个双向绑定value值直接用多个v-model传就好了;同时也将v-model默认传的prop名称由value改成了modelValue:

<child-component 
    v-model="msg">
</child-component>

<!-- 相当于 -->
<child-component 
  :modelValue="msg"
  @update:modelValue="msg = $event">
</child-component>

如果我们想通过v-model传递多个值,可以将一个argument传递给v-model:

<child-component 
    v-model.msg1="msg1"
    v-model.msg2="msg2">
</child-component>

<!-- 相当于 -->
<child-component 
    :msg1="msg1" 
    @update:msg1="msg1=$event"
    :msg2="msg2"
    @update:msg2="msg2=$event">
</child-component>

写在最后的话,如果文章对您有帮助请点下赞

举报

相关推荐

0 条评论