gpt4 book ai didi

vue.js - 每次路线更改时重复键 Vuex Getters

转载 作者:行者123 更新时间:2023-12-05 06:22:55 25 4
gpt4 key购买 nike

我正在从 firebase 获取一组对象,并使用 V-for 以列表格式向它们显示字符组件。每次我转到主页并返回字符页面时,列表都会成倍增加并显示重复的键。

characters.vue:

<template>
<ul class="characters-list">
<li v-for="allHero in getAllHeros" v-bind:key="allHero.id">
<router-link :to="{ name: 'characterDetail', params: { id: allHero.id } }">
<div class="hero-thumbnail">
<img :src="allHero.imageUrl" :alt="allHero.title" />
</div>
<div class="hero-detail">
<h3>{{ allHero.name }}</h3>
</div>
</router-link>
</li>
</ul>
</template>

import database from "@/firebase/init";
computed: {
...mapGetters({ getAllHeros: "getAllHeros" }),
},

created() {
database
.collection("heros")
.get()
.then(snapshot => {
snapshot.forEach(doc => {
let heros = doc.data();
heros.id = doc.id;
this.$store.dispatch('fetchAllHeros', heros)
});
});
}

VUEX 模块 -

const state = {
allHeros: []
};

const getters = {
getAllHeros: state => {
return state.allHeros;
}
};

const actions = {
async fetchAllHeros({ commit }, heros) {
commit("setAllHeros", heros);
}
};

const mutations = {
setAllHeros: (state, payload) => {
state.allHeros.push(payload);
}
};

最佳答案

当你路由到一个新页面时,你的 Vuex store 不一定会重置到它的初始状态。因此,每次创建该组件时,您都会向 vuex 存储添加更多英雄,这会导致添加重复的英雄。

为防止这种情况,您可以使用一些简单的逻辑来检查是否已加载任何英雄:

created() {
if(this.getAllHeros.length == 0){
//Get heros from database..
};
}

关于vue.js - 每次路线更改时重复键 Vuex Getters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58861384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com