2017-03-06 68 views
10

剛剛遇到我之前沒有遇到的此錯誤:「您正在將v模型直接綁定到v-for迭代別名。能夠修改v-for源數組,因爲寫入別名就像修改函數局部變量一樣。考慮使用一個對象數組,並在對象屬性上使用v-model。「我有點困惑,因爲我似乎沒有做任何錯誤的事情。從其他V-的唯一的區別環路我以前用的是這個人是一個稍微簡單一些,因爲它只是通過一個字符串數組循環,而不是對象:「您正在將v模型直接綁定到v-for迭代別名」

<tr v-for="(run, index) in this.settings.runs"> 

    <td> 
     <text-field :name="'run'+index" v-model="run"/> 
    </td> 

    <td> 
     <button @click.prevent="removeRun(index)">X</button> 
    </td> 

</tr> 

該錯誤消息似乎建議我需要讓事情變得更加複雜一點,並且使用對象而不是簡單的字符串,這在某種程度上對我來說並不合適。我錯過了什麼嗎?

+0

如何'settings'在你的視圖模型中定義? –

+0

'settings'是從服務器返回的JSON對象,包含名爲'runs'的屬性,最初是一個空數組。 –

回答

22

由於您使用的是v-model,因此您希望能夠從輸入字段更新run值(text-field是基於文本輸入字段的組件,我假設)。

該消息告訴你,你不能直接修改一個v-for別名(其中run是)。相反,您可以使用index來引用所需的元素。您可以在removeRun中同樣使用index

new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    settings: { 
 
     runs: [1, 2, 3] 
 
    } 
 
    }, 
 
    methods: { 
 
    removeRun: function(i) { 
 
     console.log("Remove", i); 
 
     this.settings.runs.splice(i,1); 
 
    } 
 
    } 
 
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script> 
 
<table id="app"> 
 
    <tr v-for="(run, index) in settings.runs"> 
 

 
    <td> 
 
     <input type="text" :name="'run'+index" v-model="settings.runs[index]" /> 
 
    </td> 
 

 
    <td> 
 
     <button @click.prevent="removeRun(index)">X</button> 
 
    </td> 
 

 
    <td> 
 
     {{run}} 
 
    </td> 
 

 
    </tr> 
 
</table>

+3

優秀!這樣做,謝謝,沒有增加額外的複雜性。 –

+2

它應該在文檔中。我很難找到它。 –