javascript - Vue 和 Axios 的投票按钮
问题描述
我的应用中有一个投票按钮,可以为文章或评论投票。我几乎可以使用 ajax,但点击和计数器的同步是个大问题。我现在尝试用 vue js 来做,因为有人建议这样做,指的是Sync vote button with backend vote function。
我不得不说我是 vue js 的新手,希望有人可以帮助我让它工作。一个小规范,我希望它如何工作。用户可以切换投票按钮,使其添加 +1 或 0,并像在堆栈上一样更改颜色,但只能使用向上按钮。
我现在所拥有的将请求发送到后端并将投票存储在数据库中,但我不知道如何正确设置计数器和颜色。到目前为止我所拥有的。
<template>
<div>
<a class="vote" :class="{ active: hasVotes }" @click="vote"></a>
<div class="points">{{ votes }}</div>
</div>
</template>
<script>
export default {
data(){
return{
votes: this.voted
}
},
props: {
voted: {
required: true,
type: Number
},
article: {
required: true,
type: Object
}
},
computed: {
hasVotes() {
return this.votes > 0;
}
},
methods:{
vote(){
axios.post('/article/vote/' + this.article.id)
.then(function (response) {
console.log(response.data);
this.votes = response.count;
});
}
}
}
</script>
我还要说的是,它是一个集成了 vue.js 的 laravel 5.7 应用程序。也许最好用组件来做......?
最好的
解决方案
将其封装在组件中会更容易,因为 Vue 是数据驱动的,现在您实际上必须深入 DOM 并在计数大于 0 时为特定箭头操作箭头颜色。
我已经更改并简化了您的代码示例。您要做的第一件事是没有单独的votes
和voteCount
属性,因为它们只是同一个东西。您希望通过文章道具从后端接收初始投票,并通过您的 XHR 调用对其进行更新。
我已经模拟了一个我没有测试过的快速示例,但这应该会让你朝着正确的方向前进。
例子:
<upvote-arrow :article="{{ $article }}"></upvote-arrow>
零件:
<template>
<div>
<a class="arrow" :class="{ active: hasVotes }" @click="vote"></a>
<div class="points">{{ votes }}</div>
</div>
</template>
<script>
export default {
data(){
return{
votes: this.article.votes
}
},
props: {
article: {
required: true,
type: Object
}
},
computed: {
hasVotes() {
return this.votes > 0;
}
},
methods:{
vote(){
axios.post('/article/vote/' + this.article.id)
.then(function (response) {
this.votes = response.count;
});
}
}
}
</script>
<style lang="scss" scoped>
.active {
border-color: transparent transparent #1267dc transparent;
}
</style>
active
当您拥有超过 1 票时,一个类将被应用到具有计算属性的锚点。使用这种样式绑定,您可以更改箭头的颜色。
仅在 XHR 调用实际成功时更改投票也是一个更好的主意,因为它可能由于某种原因而失败,并且在这种情况下不会反映正确的状态。只需使用后端的响应更新投票。
推荐阅读
- javascript - 如何使用事件监听器加载 javascript 文件
- regex - 正则表达式替换等号后的文本
- java - 以某种方式传递URL字符串时无法建立Jsoup连接
- python - 使用 panda 方法更改单独的类型
- r - R计数值在连续日期中的出现
- python - Python Async 装饰器保留输入
- c# - 如何使用 System.CommandLine.DragonFruit 将枚举定义为 CLI 选项?
- django - filterset_fields 的 drf-spectacular 问题
- c++ - 如何在 C++ 中增加 rdbuf 使用的缓冲区大小
- python - 当我更改副本字典时,为什么原始字典的元素会发生变化?