2017-07-26 111 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