所以基本上我有2个组件,我使用 webkit simple-template 来组织我的代码,在我的项目中我有一个问题,基本上我有一个类似文本区域的东西,每次我在那里写东西时,它应该显示一个 div该文本,所以在我的文本区域组件中我做了这样的事情:
<template>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-offset-3 col-md-6">
<label>Quote:</label>
<textarea v-model="quote.text" class="form-control" rows="5"></textarea>
<div class="text-center">
<button @click="addQuote" class="btn btn-primary center">Add Quote</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { quoteBus } from '../main.js';
export default {
methods: {
addQuote() {
if (this.counter < 10) {
this.counter++;
this.quote.id = this.counter;
quoteBus.$emit('saveQuote', this.quote);
}
}
},
data: function () {
return {
quote: {},
counter: 0
}
},
created(){
quoteBus.$on('decreaseCounter', () => {
this.counter--
});
}
}
</script>
每次我添加引号(文本)时,我都会调用另一个组件中的事件,该事件应该将对象取消移动到数组中。
组件二(带 div)
<template>
<div class="row">
<div class="col-md-3" v-for="(quote,$index) in quotes" @click="deleteQuote($index)">
<div class="spacing">
<h2>{{quote.text}}</h2>
</div>
</div>
</div>
</template>
<script>
import { quoteBus } from '../main.js';
export default {
data: function () {
return {
quotes: []
}
},
methods: {
deleteQuote(i){
this.quotes.splice(i,1);
quoteBus.$emit('decreaseCounter');
}
},
created() {
quoteBus.$on('saveQuote', quote => {
this.quotes.unshift(quote);
console.log(quote);
});
}
}
</script>
正如你们所看到的,这里我有 unshift 将对象添加到数组的开头,并且在 html 上面我做了一个 v-for 来迭代数组,一切都很好,但是显示了 div很奇怪,这是行为:
我在文本区域上放置了“一些文本”,一切都很好,我得到了一个带有“一些文本”的 div
然后我将“some Text2”放在文本区域上,并且“some Text2”覆盖了前一个对象,我得到所有div都显示了最后输入的文本,所以想象一下在我的第9个div中我输入“abc”全部其他8个div得到'abc',我希望你们理解这个问题。
Ps:console.log(quote)很好地显示了我想要取消移动的对象,这正是我想要传递给数组的对象,所以那里没有问题。
谢谢大家,
抱歉,帖子太长了
报价日志:
首先添加:
Array[1]0: Object__ob__: Observerid: 2text: "second"__proto__: Object1: Object__ob__: Observerid: 2text: "second"__proto__: Object__ob__: Observerlength: 2__proto__: Array
第二个添加:
Array[1]0: Object__ob__: Observerid: 2text: "second"proto: Object1: Object__ob__: Observerid: 2text: "second"proto: Object__ob__: Observerlength : 2__proto__: 数组
最佳答案
问题是您需要一个唯一标识每个元素的键。 https://v2.vuejs.org/v2/guide/list.html#key 我建议添加这个
this.quote.id = this.counter;
this.quote.key = + new Date();//new property
然后在你的其他组件中
<div class="col-md-3" v-for="(quote,$index) in quotes" @click="deleteQuote($index)" :key="quote.key">
不要使用您的 ID 作为键,因为它会根据报价在数组中的位置而变化。
关于javascript - 对象数据覆盖所有以前的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42911403/