首页 > 解决方案 > VueJS组件不刷新Axios GET请求虽然有一个关键

问题描述

我构建了一个包含组件“投票”的组件“文章”。你可能已经猜到了:每篇文章都有正票和负票。我在“Article.vue”中这样称呼我的投票组件:

<votes :voteId="$route.params.id" type="actu" :key="'actuVote-'+$route.params.id"/>

这是我的投票部分:

<template>
  <div :key="`vote-${type}-${voteId}`">
    <span>
      <span
        class="vote"
        :class="{ selectionne: voteUser === 'POSITIF' }"
        @click="e => vote(e.target,voteId,'POSITIF')">
        
      </span>
      {{ votes.pos }}
    </span>
    <span>
      <span
        class="vote"
        :class="{ selectionne: voteUser === 'NEGATIF' }"
        @click="e => vote(e.target,voteId,'NEGATIF')">
        
      </span>
      {{ votes.neg }}
    </span>
  </div>
</template>

<script>
import {
  defineComponent, onMounted, toRefs, ref,
} from 'vue';

import axios from 'axios';

export default defineComponent({
  name: 'Votes',
  props: ['voteId', 'type'],
  setup(props) {
    console.log(JSON.stringify(props));
    const { voteId, type } = toRefs(props);
    const votes = ref({
      pos: 0,
      neg: 0,
    });
    const voteUser = ref('');

    async function fetchVotes(idVote, typeVote) {
      const res = await axios.get(`${process.env.VUE_APP_API_URL}/votes/${idVote}/${typeVote}`);
      try {
        votes.value.neg = +res.data.filter((x) => x.vote === 'NEGATIF')[0].nombre;
      } catch (e) {
        console.log(`Pas de vote négatif: ${e}`);
      }
      try {
        votes.value.pos = +res.data.filter((x) => x.vote === 'POSITIF')[0].nombre;
      } catch (e) {
        console.log(`Pas de vote positif: ${e}`);
      }
    }

    async function verifVote(idVote) {
      const res = await axios.get(`${process.env.VUE_APP_API_URL}/votes/verif/${type.value}/${idVote}`);
      if (res.data.length > 0) {
        voteUser.value = res.data[0].vote;
      }
    }

    async function vote(elt, idVote, typeVote) {
      if (!elt.classList.contains('recherche')) {
        elt.classList.toggle('recherche');
        const res = await axios.post(`${process.env.VUE_APP_API_URL}/votes/`, { id: idVote, type: type.value, vote: typeVote });
        if (res.data.length > 0) {
          votes.value[typeVote === 'POSITIF' ? 'pos' : 'neg'] += 1;
          if (typeVote !== voteUser.value && voteUser.value !== '') {
            votes.value[typeVote === 'POSITIF' ? 'neg' : 'pos'] -= 1;
          }
        } else {
          votes.value[typeVote === 'POSITIF' ? 'pos' : 'neg'] -= 1;
        }
        voteUser.value = res.data;
        elt.classList.toggle('recherche');
      }
    }

    onMounted(async () => {
      fetchVotes(voteId.value, type.value);
      verifVote(voteId.value, type.value);
    });

    return {
      votes,
      vote,
      voteUser,
    };
  },
});
</script>

<style scoped>
.vote {
  cursor: pointer;
}

@keyframes fade {
    from { opacity: 1.0; }
    50% { opacity: 0.2; }
    to { opacity: 1.0; }
}

.recherche {
  animation:fade 500ms infinite;
}

.selectionne {
  border: 1px solid black;
  padding: 3px;
  background-color: rgba(0,0,255,0.5);
  border-radius: 3px;
}
</style>

我的问题是:当我打开时actu/1,我投了赞成票,然后我继续actu/2投反对票,如果我回到actu/1,正确的文章加载正确,但我的投票好像我之前的投票actu/1不是考虑到。如果我刷新actu/1并且actu/2不投票,一切都很好,正确的投票正确显示。

当我查看网络控制台时,我看到 200 HTTP 代码是特殊的:200 OK (from disk cache). 也许有一种方法可以强制 axios 真正再次发出 HTTP 请求。

我试过这个,但它破坏了我的应用程序中的所有内容:

axiosInstance.defaults.headers = {
  'Cache-Control': 'no-cache',
  Pragma: 'no-cache',
  Expires: '0',
};

我在这里做错了什么?提前致谢 :)

标签: vue.jsaxiosvue-componentvuejs3

解决方案


推荐阅读