我正在构建一个类似于 stackoverflow 的问答网站,您可以在其中投票
问题
或答案
。为了简化,我保留了投票代码。
这是vote
组件,用于question
和answer
组件。
<template>
<div class="vote">
<h4 @click="voteUp">
<i :class="{'fa fa-chevron-circle-up' : votedUp>-1, 'fa fa-chevron-up': votedUp==-1 }"></i>
</h4>
</div>
</template>
<script>
export default {
props: ['votes','item'],
computed:{
votedUp() {
return _.findIndex(this.votes, {user_id: this.$root.authuser.id});
}
},
methods:{
voteUp() {
axios.post(this.$root.baseUrl+'/vote_item', {item_id:this.item.id,item_model:this.item.model,vote:'up'})
.then(response => {
_.isEmpty(response.data) ? this.votes.splice(this.votedUp,1) : this.votes.push(response.data);
})
}
}
}
</script>
这是使用vote
组件的question
组件:
<template>
<div class="question">
<h1>{{ question.title }}</h1>
<div class="row">
<div class="col-xs-1">
<vote :votes="question.votes" :item="item"></vote>
</div>
<div class="col-xs-11 pb-15">
<p>{{ question.body }}</p>
<comment-list :comments="question.comments" :item="item" ></comment-list>
</div>
</div>
<answer v-for="answer in question.answers" :answer="answer"></answer>
</div>
</template>
<script>
export default {
props: ['question'],
data(){
return {
item:{ id:this.question.id, model:'Question' }
};
}
}
</script>
这是使用 vote
组件的 answer
组件:
<template>
<div class="answer row">
<div class="col-xs-1 mt-20">
<vote :votes="answer.votes" :item="item"></vote>
</div>
<div class="col-xs-11">
<h3>{{ answer.title }}</h3>
<p>{{ answer.body }}</p>
<comment-list :comments="answer.comments" :item="item" ></comment-list>
</div>
</div>
</template>
<script>
export default {
props: ['answer'],
data(){
return {
item:{ id:this.answer.id, model:'Answer' }
};
}
}
</script>
问题
投票工作正常,并且会更改 question.votes
和 answer.votes
的状态,但它仅呈现 answers
的 HTML 。我必须刷新才能看到对问题
的赞成票。同样在 Vue 开发者工具控制台中,answer.votes
会自动刷新,而我需要点击 vue 刷新按钮才能看到 question.votes
将新投票考虑在内(但仍然如此)没有 HTML 渲染)。
重要说明
正如您所看到的,您还可以对问题
和答案
进行评论
,这对两者都适用,因为我使用了不同的$emit
事件的方法。也许这是我答案的解决方案,但我真正想知道的是为什么投票
中的功能适用于答案
而不是问题
。
谢谢!
最佳答案
您的vote
组件不应改变props
。改变本地副本:
export default {
props: ['votes','item'],
data() {
return { votesCopy: [] };
},
mounted() {
this.votesCopy = this.votes.slice();
},
computed:{
votedUp() {
return _.findIndex(this.votesCopy, {user_id: this.$root.authuser.id});
}
},
methods:{
voteUp() {
axios.post(this.$root.baseUrl+'/vote_item', {item_id:this.item.id,item_model:this.item.model,vote:'up'})
.then(response => {
_.isEmpty(response.data)
? this.votesCopy.splice(this.votedUp,1)
: this.votesCopy.push(response.data);
})
}
}
}
关于javascript - Vue.js 2.0 在一个项目上渲染相同的组件,但不在另一个项目上渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42381718/