简体   繁体   English

添加到列表中的项目在Vue.js的第2版中是非反应性的

[英]Items added to list are non-reactive in version 2 of Vue.js

In Vue 1.0 I used to add items to an array used in a v-for by simply calling items.push({}) as you can see here: 在Vue 1.0中,我曾经通过简单地调用items.push({})将项添加到v-for中使用的数组中,如下所示:

http://jsbin.com/figiluteni/1/edit?html,js,output http://jsbin.com/figiluteni/1/edit?html,js,output

The exact same code in Vue 2.0 inserts a non-reactive object to the array: Vue 2.0中完全相同的代码将非反应对象插入到数组中:

http://jsbin.com/zuwihahiwa/1/edit?html,js,output http://jsbin.com/zuwihahiwa/1/edit?html,js,output

(Note that the newly added items are not live updated when edited) (请注意,新添加的项目在编辑时不会实时更新)

    <button @click="items.push({})">Add item</button>

I know that Vue inserts hooks on arrays when initialized, but being a Vue model binding that creates the new item's "name" property, I thought it could be automatically hooked like in Vue 1. 我知道Vue在初始化时会在数组上插入钩子,但是作为Vue模型绑定会创建新项目的“name”属性,我认为它可以像在Vue 1中一样自动挂钩。

I find this new behavior very inconvenient, for it forces me to add a prototype of the object I want to add in Vue's data and clone it: 我发现这种新行为非常不方便,因为它迫使我在Vue的数据中添加我想要添加的对象的原型并克隆它:

http://jsbin.com/bamasobuti/1/edit?html,js,output http://jsbin.com/bamasobuti/1/edit?html,js,output

In Vue's data: 在Vue的数据中:

    item_prototype: {id: null, name: ""} 

In the template: 在模板中:

    <button @click="items.push(_.clone(item_prototype))">Add item</button>

My question is: Is there a recommended way of adding elements without having to keep a prototype of an empty element? 我的问题是:是否有一种推荐的添加元素的方法,而不必保留空元素的原型?

The change is not related to reactivity system change, but rather how v-model works in 2.0: it no longer magically creates non-existent paths and make them reactive for you. 这种变化与反应系统的变化无关,而是与v-model在2.0中的工作方式有关:它不再神奇地创建不存在的路径并使它们对你有反应。

This change is intended to force you to think about your data shape and to make your application state more predictable, similar to how you are expected to declare the reactive properties in your component's data option. 此更改旨在强制您考虑数据形状并使应用程序状态更具可预测性,类似于在组件的data选项中声明反应属性的方式。

If I were you, I'd create a method and just do this.items.push({ id: null, name: '' }) . 如果我是你,我会创建一个方法,然后执行this.items.push({ id: null, name: '' }) There's no need to clone it. 没有必要克隆它。

According Vue's documentation, v-model="item.prop" is just syntactic sugar for: 根据Vue的文档, v-model="item.prop"只是语法糖:

v-bind:value="item.prop" v-on:input="item.prop = $event.target.value" . v-bind:value="item.prop" v-on:input="item.prop = $event.target.value"

To make it work, just stop using v-model="item.prop" and use this instead: 要使它工作,只需停止使用v-model="item.prop"并使用它代替:

:value="item.prop" @input="$set(item,'prop',$event.target.value)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM