【发布时间】:2021-04-03 22:45:11
【问题描述】:
我的项目有问题。该项目就像stackoverflow。问题/答案。当我单击向上或向下按钮说此解决方案是否有用时,它会发送到后端以增加并发送回更新的所有解决方案。目前一切正常。但是在我更新了变异的解决方案后,解决方案消失了,但它更新了数组。它适用于问题部分。 v-for 不用于问题部分。我认为 v-for 和 v-if 可能会导致问题。好的,这里是代码:
HTML
<b-card
no-body
v-for="(solution, index) in solutionsOfProblem"
:key="index"
>
<div v-if="solutionsOfProblem.length > 0">
<b-card-body id="problem-detail-body">
<div id="problem-detail-body-top">
<div id="problem-detail-body-top-left">
<button
@click="upSolution(solution._id)"
id="up-down-buttons"
>
<b-icon-exclamation-circle-fill
id="up-icon"
variant="danger"
class="h2 mb-2"
></b-icon-exclamation-circle-fill>
...
...
script.js
computed: {
user() {
return this.$store.state.user.user;
},
solutionToSend() {
return this.$store.state.solutions.solutionToSend;
},
solutionsOfProblem() { // this shows the array of solutions
return this.$store.state.solutions.solutionsOfProblem
},
methods: {
upSolution(solution) { // this one trigger the action to make a post request to database
if (this.user.name) {
this.voteSolution.solutionId = solution
this.voteSolution.isUpped = true
this.$store.dispatch('solutions/voteSolutionFromDatabase', this.voteSolution)
} else {
this.$bvToast.toast('You need to login to vote!', {
title: 'Error',
autoHideDelay: 4000,
variant: 'danger'
})
}
},
}
变异
const solutionVoted = (state, solution) => {
state.solutionsOfProblem = solution
}
状态
solutionsOfProblem: [],
actions.js - 我从数据库中获取数组
const voteSolutionFromDatabase = ({ commit }, vote) => {
axios({
method: 'post',
url: 'http://localhost:3000/api/solution/votesolution',
data: vote,
withCredentials: true,
headers: {
Accept: "application/json",
},
})
.then((res) => {
commit('solutionVoted', res.data.data)
})
.catch((err) => {
commit('votedSolutionError', err.response)
})
}
如果有任何其他方法可以更新数组或我的代码有问题,我想听听。提前致谢。
【问题讨论】:
-
我看到的断开连接是您的突变更新了
state.solutionsOfProblem,但您的组件的计算属性使用了state.solutions.solutionsOfProblem(注意solutions对象)。假设这不是一个错字,这两者在您的代码中是如何链接的?另外,请显示res.data.data的值。