我试图创建一个关注按钮,已经编写了代码,所以当用户关注时,它直接进入数据库,用户ID和跟随的用户ID,在组件中,我编写了一个代码来检查是否用户已经被跟踪返回true和false,然后如果following true,则应该显示following,反之亦然,但是到目前为止,每当页面加载时,它都会显示true时显示follow,如果我转到另一个页面并返回,它将返回显示以下错误信息,直到我再次刷新整个页面
<template>
<button v-bind:class="{followVendor:!following,followingVendor:following}"
type="button"
@click="followToggle"
class=" btn btn-sm btn-outline">
{{followText}}</button>
</template>
data:{
userFollowing:{},
following: false,
followText:'follow',
}
mounted(){
axios.get(`/api/user-following`,
{
headers: { Authorization: `Bearer ${this.user.access_token}` }
}).then(
response=>{
if (response.status === 200) {
this.userFollowing = response.data;
this.writer=true;
if (this.userFollowing.length > 0) {
if (this.userFollowing[0].user_id === this.user.id && this.userFollowing[0].vendorId === this.writterD.id) {
this.following = true;
this.followText = 'following';
}
}
}
}
)
}
methods: {
follow(params, name) {
let data = {
vendorName: name,
vendorId: params
};
if (this.auth) {
axios
.post("/api/user-following", JSON.parse(JSON.stringify(data)), {
headers: { Authorization: `Bearer ${this.token}` }
})
.then(response => {
if (response.status === 201) {
this.following = true;
this.followText = 'following';
this.$toasted.success("Successfully followed");
} else if (response.data === " Already following") {
this.$toasted.error("Already following");
} else {
this.$toasted.error("Error");
}
})
.catch(error => {
console.log(error);
});
} else {
this.$toasted.error("You have to log in to follow");
}
},
unFollow(){
let vendor = this.writterD.id;
let unfollow = confirm(`unfollow ${this.writterD.storeName}?`)
if (unfollow) {
axios.delete(`/api/user-following/${vendor}`,
{headers: {Authorization: `Bearer ${this.token}`}}).
then(response=>{
if (response.status === 200) {
this.following = false;
this.followText = 'follow';
this.$toasted.success("Successfully Unfollowed");
}else{
this.$toasted.error("Already Unfollowed");
}
})
}
},
followToggle(){
this.following? this.unFollow(): this.follow(this.writterD.id, this.writterD.storeName);
},
}
即使我不重新加载整个页面,我如何才能使其始终显示正确的页面
答案 0 :(得分:1)
您需要执行的是强制重新渲染,最好的方法是在需要更新的组件上放置key
,然后在更新信息时更改密钥。更新密钥后,数据将更新,因为组件将重新呈现。像这样:
<button :key="update" v-bind:class="{followVendor:!following,followingVendor:following}"
type="button"
@click="followToggle"
class=" btn btn-sm btn-outline">
{{followText}}</button>
...
data(){
return {
update: 0
}
}
...
this.followText = 'following';
this.update++
有关此主题的一篇不错的文章,请参见此处: https://michaelnthiessen.com/force-re-render