为了账号安全,请及时绑定邮箱和手机立即绑定

axios 和 vuex 正在删除数组中的错误索引

axios 和 vuex 正在删除数组中的错误索引

PHP
斯蒂芬大帝 2021-11-26 16:38:31
你好,我有一个 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 对象。


查看完整回答
反对 回复 2021-11-26
  • 1 回答
  • 0 关注
  • 129 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信