首页 > 解决方案 > 当我通过路由器链接访问 URL 时,组件中的 Vue.js v-for 会呈现,但是如果我手动键入 URL 或刷新页面,则 v-for 不会呈现

问题描述

我有一个非常简单的视图,可以显示某个游戏中所有角色的图标。如果我要通过路由器链接访问显示该视图的 URL,一切正常,我会看到图标,但是,如果我随后刷新页面,图标就会消失。

如果我手动输入它们,它们也根本不会呈现www.example.com/champions。为什么会这样。

我的组件:

<template>
    <div class='wrapper'>
        <div class="champions-container">
            <div v-for='champion in champions' class="champion">
                <img class='responsive-image' :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/champion/' + champion.image.full" alt="">
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data(){
            return {
                champions: this.$store.state.fullChampions
            }
        }
    }
</script>

还有我存储冠军的 Vuex 商店:

export default new Vuex.Store({
    state: {
        version: null,
        fullChampions: null
    },
    mutations: {
        version(state, data){
            state.version = data.version
        },
        fullChampions(state, data){
            state.fullChampions = data.fullChampions
        }
    },
    actions: {
        getVersion({commit}){
            return axios.get("http://ddragon.leagueoflegends.com/api/versions.json")
            .then((response) => {
                commit('version', {
                    version: response.data[0]
                })
            })
            .catch(function (error) {
                console.log(error);
            })
        },
        getFullChampions({commit, state}){
            return axios.get("https://ddragon.leagueoflegends.com/cdn/" + state.version + "/data/en_US/championFull.json")
            .then((response) => {
                commit('fullChampions', {
                    fullChampions: Object.values(response.data.data)
                })
            })
            .catch(function (error) {
                console.log(error);
            })
        },

标签: javascriptvue.js

解决方案


这些可能是因为您遇到了这些问题。

首先:该组件不是在您的 vuex 中调度您的 getFullChampions 函数的组件,可能在其他组件中。

其次,您已经分配了未更新状态 fullChampions 的冠军值。

this.champions: this.$store.state.fullChampions // state.fullChampions might not yet updated.

试试这个可能对你有帮助

watch: {
      '$store.state.fullChampions': function() {
           this.champions = this.$store.state.fullChampions  
      },
}

最后是首先在您的 v-for 之上做一个条件以防止该元素

<div class="champions-container" v-if=""$store.getters.version>
    <div v-for='champion in champions' class="champion">
        <img class='responsive-image' :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/champion/' + champion.image.full" alt="">
    </div>
</div>

推荐阅读