我正在建立一个用户可以上传帖子的网站。每个用户都有一个个人资料页面,他们可以在其中查看他们喜欢的帖子以及他们创建的帖子。在创建的帖子上方有一个删除按钮。当我删除帖子时,它会被删除,但只能从后端删除。在主页和个人资料页面上(如果我再次进入个人资料页面),帖子仍然存在。如果我刷新页面一切正常,但必须有一种方法可以在不刷新的情况下实现这一点,对吧?
我无法重新渲染组件。如您所见,我对编程很陌生。使用这种删除方法,我需要更新 3 个组件(Home.vue、Posts.vue 和 Profile.vue)。
我的个人资料组件/页面的删除按钮 html:
<v-container class="mt-3" v-else>
<v-flex xs12>
<h2 class="font-weight-light">
Created posts
<span class="font-weight-regular">({{ userPosts.length }})</span>
</h2>
</v-flex>
<v-layout row wrap>
<v-flex xs12 sm6 v-for="post in userPosts" :key="post._id">
<v-card class="mt-3 ml-1 mr-2" hover>
<v-btn color="info" floating fab small dark @click="loadPost(post)">
<v-icon>edit</v-icon>
</v-btn>
<v-btn
color="error"
floating
fab
small
dark
@click="handleDeleteUserPost(post)"
>
<v-icon>delete</v-icon>
</v-btn>
<v-img
height="30vh"
:src="post.imageUrl"
@click="goToPost(post._id)"
></v-img>
<v-card-text>{{ post.title }}</v-card-text>
</v-card>
</v-flex>
</v-layout>
</v-container>
下面的生命周期挂钩。它在“方法”下:
handleDeleteUserPost(post) {
this.loadPost(post, false);
const deletePost = window.confirm("Do you want to delete your post?");
if (deletePost) {
this.$store.dispatch("deleteUserPost", {
postId: this.postId,
});
}
}
vuex store 组件的删除功能。它在“行动”下:
deleteUserPost: ({ state, commit }, payload) => {
apolloClient
.mutate({
mutation: DELETE_USER_POST,
variables: payload,
})
.then(({ data }) => {
const index = state.userPosts.findIndex(
(post) => post._id === data.deleteUserPost._id
);
const userPosts = [
...state.userPosts.slice(0, index),
...state.userPosts.slice(index + 1),
];
commit("setUserPosts", userPosts);
})
.catch((err) => {
console.error(err);
});
}
来自“商店”的突变
mutations: {
setPosts: (state, payload) => {
state.posts = payload;
},
setSearchResults: (state, payload) => {
if (payload !== null) {
state.searchResults = payload;
}
},
setUser: (state, payload) => {
state.user = payload;
},
setUserPosts: (state, payload) => {
state.userPosts = payload;
},
setLoading: (state, payload) => {
state.loading = payload;
},
setError: (state, payload) => {
state.error = payload;
},
setAuthError: (state, payload) => {
state.authError = payload;
},
clearUser: (state) => (state.user = null),
clearError: (state) => (state.error = null),
clearSearchResults: (state) => (state.searchResults = []),
},