2017-07-26 112 views
1

在我VUE应用程序,我已经得到了很多很多的输入字段(例如)的:Vue.js同步输入字段

<div class="field"> 
    <label for="name" class="label">Naam</label> 

    <div class="control"> 
     <input id="name" 
       name="name" 
       type="text" 
       v-model="relation.name" 
       class="input" 
       :class="{ 'is-danger': errorsHas('name') }" 
       autofocus> 

     <p class="help is-danger" v-if="errorsHas('name')">{{ error('name') }}</p> 
    </div> 
</div> 

所以我想在一个input组件这个包起来。但是由于vue 1 .sync方法不存在,所以我该怎么做?我猜,射击事件并不是一个真正的解决方案。想知道如何解决这个问题?

我想有这样的事情:

<custom-input v-model=relation.name></custom-input> 

和其他一切(类名,自动对焦等)必须在组件来处理。

这可能吗?

回答

5

同步调节剂在2.3.0+重新,见Vue Js Docs

在2.3.0+我们重新引入了道具.SYNC修改,但是这一次它只是语法糖,可以自动扩展到一个额外的V系列监听器:

以下<comp :foo.sync="bar"></comp>扩展为:

<comp :foo="bar" @update:foo="val => bar = val"></comp> 

对于孩子组件更新Foo的价值,它需要明确地发出一个事件,而不是突变的道具:

this.$emit('update:foo', newValue) 

您可能会看到这个fiddle为例。

+0

正是我需要的!但是何时何地我会开火:'this。$ emit('update:foo',newValue)'? – Jenssen

+0

@Jenssen在你的例子中,你试图更新的属性是什么? – enriqg9

+0

我正在尝试更新父组件中的'relation.name'。 – Jenssen

0

您可以使用props更具体dynamic props

只需在您的组件v-model中设置一个适当的组件,该组件接受prop并引用该prop

你的组件可以是这样的(调整例如,从official site):

Vue.component('custom-input', { 
    // declare the props 
    props: ['message'], 
    // just like data, the prop can be used inside templates 
    // and is also made available in the vm as this.message 
    template: '<input v-model="message">' 
}) 

虽然你的父母会使用这样的:

<custom-input :message="parentMsg"></custom-input> 
+0

谢谢。但后来我得到:'避免直接改变一个道具,因为只要父组件重新渲染,该值就会被覆盖。相反,使用基于道具值的数据或计算属性。支柱正在发生变异:“名字” – Jenssen