你好,我有一個 laravel 和 vuejs 的問題,我的問題是,當我嘗試從我的商店文件中的帖子中刪除帖子時,它總是刪除數組的第一個對象,但在數據庫中它刪除了正確的行這是我的商店文件state: { posts:[] },getters: { posts:state=> { return state.posts } },mutations: { AllPosts:(state,payload)=>{ state.posts=payload; }, DeletePost:(state,payload)=>{ state.posts.splice(payload,1); } },actions: { AllPosts:({commit},payload)=>{ commit("AllPosts",payload) }, DeletePost:({commit},payload)=>{ commit("DeletePost",payload) } }這是我在 postcontroller 中的銷毀函數public function destroy($id) { $post=Post::find($id); $post->delete(); return response()->json($post,200); }這是我的 axiosdeletepost(id) { axios.delete("/admin/posts/delete/"+id) .then(res=> { this.$store.dispatch("DeletePost",res.data) console.log(res.data) }) },這是代碼的html部分<tr v-for="(post,i) in allposts" :key="post.id"> <td>{{post.id}}</td> <td>{{post.category}}</td> <td v-if="post.title.length<30">{{post.title}}</td> <td v-else>{{ post.title.substring(0,30)+"..." }}</td> <td v-if="post.shortly.length<30">{{post.shortly}}</td> <td v-else>{{ post.shortly.substring(0,30)+"..." }}</td> <td><img height="100px" width="100px" :title=imagealt(i) :src="image(i)" :alt="imagealt(i)"></td> <td>{{post.created_at}}</td> <td><button class="delete-btn" @click.prevent="deletepost(post.id)">delete</button></td> <td><button class="edit-btn" @click.prevent="editpost(post.id)">edit</button></td> </tr>我應該怎么做才能刪除數組的正確對象?
1 回答

犯罪嫌疑人X
TA貢獻2080條經驗 獲得超4個贊
從DeletePost突變:
state.posts.splice(payload,1);
for的第一個參數splice是一個索引。您不能只是將要刪除的對象傳遞給它。
你可以這樣寫:
const index = state.posts.findIndex(post => post.id === payload.id);
if (index !== -1) {
state.posts.splice(index, 1);
}
或者也許filter改用:
state.posts = state.posts.filter(post => post.id !== payload.id);
我還考慮將id直接傳遞給突變作為有效負載,而不是傳遞整個 post 對象。
- 1 回答
- 0 關注
- 168 瀏覽
添加回答
舉報
0/150
提交
取消