Laravel 数组在修改元素时无反应,仅在添加或删除元素时
我正在用Vue组件和Laravel制作出版物的crud 我有一个名为publications.vue的父组件,它有两个子组件,分别为create.vue和list.vue,以及list.vue。我还有一个子组件,分别为remove.vue和update.vue 问题是,当我在数组中添加或删除发布时,它工作得很好,但当我修改元素时,它不会做出反应。控制器工作得很好,但除非我刷新,否则屏幕上什么也看不到 这是我的代码:Laravel 数组在修改元素时无反应,仅在添加或删除元素时,laravel,vue.js,vue-reactivity,Laravel,Vue.js,Vue Reactivity,我正在用Vue组件和Laravel制作出版物的crud 我有一个名为publications.vue的父组件,它有两个子组件,分别为create.vue和list.vue,以及list.vue。我还有一个子组件,分别为remove.vue和update.vue 问题是,当我在数组中添加或删除发布时,它工作得很好,但当我修改元素时,它不会做出反应。控制器工作得很好,但除非我刷新,否则屏幕上什么也看不到 这是我的代码: <template> <div class="
<template>
<div class="main">
<create
:user="user"
v-if="showCreate"
@create="addPublicationOnClient"
/>
<list
v-for="(publication, index) in publications"
:key="publication.id" :publication="publication" :user="user"
@deleted="deletePublicationOnClient(index)"
@updated="updatePublicationOnClient(index, ...arguments)"
/>
</div>
</template>
我真的很感激任何帮助,因为我真的卡住了,我读了很多帖子,但找不到解决方案。Vue在对象数组方面有一些非常棘手的行为 Vue正在监视您的阵列,当阵列的
.length
被修改或其某个值被修改时,Vue可以“看到”该更改
当您更新阵列中某个对象的字段时,您将无法获得反应性,因为要进行Vue,阵列尚未更改。这是因为数组的值是对对象的引用,当您更新对象时,这些引用不会更改
我觉得你上面的方法很好,但也可能会有一些奇怪的问题
我将重点介绍两种解决这些反应性问题的工具。我相信第一种方法更适合你的情况
您能否共享publications.vue的模板
addPublication(publication) {
this.publications.unshift(publication); // works perfect
},
deletePublication(index) {
this.publications.splice(index, 1); // works perfect
},
updatePublication(index, editedPublication) {
console.log(editedPublication); // shows the correct value of the edited publication
Vue.set(this.publications, index, editedPublication); // do not react. do not show anything
this.publications.splice(index, 1, editedPublication) // do not react neither. do not show anything
console.log(this.publications); // shows the correct values in the array
}
updatePublication(index, editedPublication) {
this.deletePublication(index);
this.addPublication(index, editedPublication);
}
<template>
<div class="main" :key="'updated-'+updated">
...
</template>
data() {
return {
updated: 0,
};
},
...
updatePublication(index, editedPublication) {
this.publications.splice(index, 1, editedPublication);
this.updated++;
}