首页 > 解决方案 > 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 应用程序。也许最好用组件来做......?

最好的

标签: javascriptlaravellaravel-5vue.jsaxios

解决方案


将其封装在组件中会更容易,因为 Vue 是数据驱动的,现在您实际上必须深入 DOM 并在计数大于 0 时为特定箭头操作箭头颜色。

我已经更改并简化了您的代码示例。您要做的第一件事是没有单独的votesvoteCount属性,因为它们只是同一个东西。您希望通过文章道具从后端接收初始投票,并通过您的 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 调用实际成功时更改投票也是一个更好的主意,因为它可能由于某种原因而失败,并且在这种情况下不会反映正确的状态。只需使用后端的响应更新投票。


推荐阅读