我正在创建一个按钮来收藏配方并将其保存到收藏夹页面,当用户单击该按钮时,用户id和配方id将被发送到postgres数据库中我与knex一起使用的like表中,该部分正在工作。现在,我希望当用户单击按钮时,最喜爱的配方的图标将更改,当用户再次单击按钮时,它将返回默认图标,并且数据将从数据库中排除。
我用下面的代码成功地做到了这一点,但是当重新加载页面时,一切都被撤消,当我再次单击按钮时,数据会再次保存,而不是被删除
module.exports = app => {
const { existsOrError } = app.api.validation
const save = (req, res) => {
const like = { ...req.body }
app.db('likes')
.insert(like)
.then(_ => res.status(204).send())
.catch(err => res.status(500).send(err))
}
const unlike = async (req, res) => {
try {
const rowsDeleted = await app.db('likes')
.where({ recipeId: req.params.id }).del()
try {
existsOrError(rowsDeleted, 'Deleted.')
} catch (msg) {
return res.status(400).send(msg)
}
res.status(204).send()
} catch (msg) {
res.status(500).send(msg)
}
}
return { save, unlike }
}
偶像:
<button class="heart" @click="liked()">
<font-icon v-if="isLiked" class="icon-heart-select" :icon="['fas', 'heart']"/>
<font-icon v-if="!isLiked" class="icon-heart" :icon="['far','heart']"/>
</button>
我的前端:
data: function() {
return {
recipe: {},
user: {},
users: [],
like: {},
isLiked: false
}
},
methods: {
liked() {
if(!this.isLiked) {
axios.post(`${baseApiUrl}/likes`, {
id: this.like.id,
userId: this.user.id,
recipeId: this.recipe.id
})
.then(res => {
this.isLiked = !this.isLiked
})
} else {
const id = this.recipe.id;
axios.delete(`${baseApiUrl}/recipes/${id}/likes`)
.then(() => {
this.isLiked = !this.isLiked
})
}
},
getUsers(user) {
this.user = { ...user }
this.user = JSON.parse(localStorage.getItem(userKey));
if(user) {
return user
}
},
},
mounted() {
const url = `${baseApiUrl}/recipes/${this.$route.params.id}`
axios.get(url).then(res => this.recipe = res.data)
this.getUsers()
},
我知道孤岛数据不会保存在任何地方,但我的逻辑正确吗?如何检查收藏夹配方的数据是否已保存,按钮图标是否已保存回默认值,数据是否已从数据库中删除?这是我的第一个复杂的实践项目,所以我有点迷失在这一部分
暂无答案!
目前还没有任何答案,快来回答吧!