Gom*_*oms 2 javascript arrays vue.js vuejs2
标题描述了我想要的,这是代码
当我们添加一个产品时,items如果它不存在(id 不同),一切都很好。但如果它存在,我只想修改该项目。区别在于items数组中每个项目的 id 。
例如:如果第一个,id = 1,qty = 3,然后,id = 1,qty = 3,我想更新 qty items
new Vue({
el: '#fact',
data: {
input: {
id: null,
qty: 1
},
items: []
},
methods: {
addItem() {
var item = {
id: this.input.id,
qty: this.input.qty
};
if(index = this.itemExists(item) !== false)
{
this.items.slice(index, 1, item);
return null;
}
this.items.push(item)
},
itemExists($input){
for (var i = 0, c = this.items.length; i < c; i++) {
if (this.items[i].id == $input.id) {
return i;
}
}
return false;
}
}
})Run Code Online (Sandbox Code Playgroud)
<Doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Add product</title>
</head>
<body>
<div id="fact">
<p>
<input type="text" v-model="input.id" placeholder="id of product" />
</p>
<p>
<input type="text" v-model="input.qty" placeholder="quantity of product" />
</p>
<button @click="addItem">Add</button>
<ul v-if="items.length > 0">
<li v-for="item in items">{{ item.qty + ' ' + item.id }}</li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
您可能误用了该slice方法,请更改slice为splice对我有用:
this.items.splice(index, 1, item)
Run Code Online (Sandbox Code Playgroud)
Vue 包装了观察到的数组的变异方法,因此它们也会触发视图更新。包装的方法是:
- 推()
- 流行音乐()
- 转移()
- 取消移位()
- 拼接()
- 种类()
- 逆转()
| 归档时间: |
|
| 查看次数: |
12263 次 |
| 最近记录: |