我正在寻找一种方法,以删除列表中新添加项目的绑定。
从表单添加第一个元素时,该元素已添加到列表中,但是当我要添加另一个元素时,此表单引用列表中的上一个项目,双向数据绑定有效,这是我不想要的。该表单应添加新元素,而不是指最近添加的元素。
如何执行此操作? 我可以使用v模型吗?
@EDIT
我尝试在添加元素时通过Object.assign解决此问题,但是在项目检查期间,vuex引用了这两个新元素。
暂时问题在于复选框,该复选框适用于所有新元素,而不适用于特定元素 我认为应该以某种方式禁用双向数据绑定
Vue.use(Vuetify,{
iconfont: 'fa'
});
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
reviews: [
{
name: 'Mazda',
id: 4324214,
repairs: [
{
name: 'rear window',
done: false,
},
{
name: 'backlight',
done: false,
}
]
},
{
name: 'Audi',
id: 12134145,
repairs: [
{
name: 'front tire',
done: true,
},
{
name: 'door',
done: true,
}
]
}
]
},
mutations: {
ADD_REVIEW(state, review) {
state.reviews.push(review);
},
SET_REVIEW_REPAIRS(state, { id }) {
let same = item => item.id == id;
let review = state.reviews.find(same);
let reviewIndex = state.reviews.findIndex(same);
console.log('check:',id)
let isNotComplate = review.repairs.some(val => val.done == false)
let done = (isNotComplate) ? true : false;
let mapReviewRepairs = review.repairs.map((val, key) => {
val.done = done;
return val;
});
state.reviews[reviewIndex].repairs = mapReviewRepairs;
},
},
getters: {
reviews: state => state.reviews
}
})
new Vue({
store,
el: "#app",
data: {
form: {
name: 'BMW',
repairs: [
{
name: 'front tire',
done: false,
},
{
name: 'door',
done: false,
}
]
}
},
computed: {
reviews() {
return this.$store.getters['reviews']
}
},
methods: {
add() {
let id = Math.floor((Math.random() * 10000000));
this.form.id = id;
let newReview = Object.assign({}, this.form);
this.$store.commit('ADD_REVIEW', newReview)
},
toggleRepairs(id) {
this.$store.commit('SET_REVIEW_REPAIRS', { id })
},
}
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.5.14/vuetify.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.0/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.4.0/vuetify.min.js"></script>
<div id="app">
<v-app>
<v-list>
<v-list-tile v-for="(item, index) in reviews" :key="item.id">
<v-list-tile-content>
{{ item.name }}
</v-list-tile-content>
<v-list-tile-action>
<v-icon color="black"
v-bind:class="item.repairs.some(val => val.done == false) ? 'grey--text' : 'success--text'"
@click="toggleRepairs(item.id)"
>
fas fa-check
</v-icon>
</v-list-tile-action>
</v-list-tile>
</v-list>
<h1 class="display-2">Form</h1>
<form style="width: 300px">
<v-text-field v-model="form.name" label="Car name"></v-text-field>
REPAITS: <span v-for="repair in form.repairs">{{ repair.name }},</span>
</form>
<v-btn @click="add" style="bottom: 5em;" fab dark fixed right color="secondary">
<v-icon dark>fas fa-plus</v-icon>
</v-btn>
</v-app>
</div>
@ EDIT2解决方案 Object.assign不会破坏引用。我做这个
JSON.parse(JSON.stringify(this.form))