美文网首页
v-model与.sync

v-model与.sync

作者: zzzZink | 来源:发表于2018-12-10 17:38 被阅读0次

在组件上使用v-model

  • v-model的原理
    • v-model其实只是语法糖,当我们在input标签内写上v-model后,实际上在vue内会编译为:
<!--v-model写法-->
<input type="text" v-model="value">
<!--编译后的写法-->
<input type="text"
  :value="value"
  @input="value = $event.target.value"
>

对于input不是很清楚的朋友可以去看mdn的文档:click me

那么问题来了,如果这个input是个组件(暂且叫input-component吧),我们想在父组件中使用input-component这个组件,我们能直接使用v-model进行双向绑定吗?
答案是:很遗憾,不能,因为v-model只是一个语法糖,他的原本写法上面已经提过,绑定value值,监听input事件,通过event拿到value并赋值给value。

那么我们要怎么做才能在组件上使用v-model呢?
很简单,当input-component触发input事件时,我们让他发布一个input事件,并带上$event.target.value,在父组件上,我们用v-model监听这个input事件,就能实现了

子组件:

<input type="text"
  :value="value"
  @input="$emit('input', $event.target.value);"
>

父组件:

<input-component v-model="value">

.sync

  • .sync 相当于对一个props进行双向绑定,也是一个语法糖
<!--语法糖.sync-->
<my-component :value.sync="msg" />
<!--编译后的写法-->
<my-component 
  :value="msg" 
  @update:value="(val) => msg = val"
>

当时我前几天在使用.sync的时候遇到了一些问题,vue向我发出了警告

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "selected"

意思是不允许我们直接修改props的值,这一点在文档中可以找到:

在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以修改父组件,且在父组件和子组件都没有明显的改动来源。

我们应该在 data 或者 computed 中创造一个副本来保存这个 props,而不是直接去修改它。

相关文章

网友评论

      本文标题:v-model与.sync

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