gpt4 book ai didi

typescript - Vuex 不更新组件

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:29 25 4
gpt4 key购买 nike

我正在使用 TypeScript 中的 Vue 和 Vuex 构建一个站点。 (抱歉,代码示例太长)

我有一个商店模块('musicArtists'):

const actions: ActionTree<MusicArtist[], any> = {
getAllArtists({ commit }): any {
Providers.musicArtists.getAll(
(musicArtists: MusicArtist[]) => {
console.log("MusicArtist!", musicArtists);
commit("setArtists", musicArtists);
},
(error: Error) => {
console.log("Error!", error);
},
);
},
};

const mutations: MutationTree<MusicArtist[]> = {
setArtists(state: MusicArtist[], artists: MusicArtist[]) {
state = artists;
console.log("setArtists", state, artists);
},
};

export default{
namespaced: true,
getters: {

},
state: {
artists : [],
},
mutations,
actions,
};

我有一个组件:

<template>
<div id="page-music-audio">
<Artist v-for="artist in artists" v-bind:artist="artist"/>
<h2>{{ count }}</h2>
</div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { mapState } from "vuex";
// import { Action, State } from "vuex-class";

import Artist from "@/components/music/Artist.vue";
import { MusicArtist } from "@/common/models/music-artist";
import { Providers } from "@/providers";
import store from "@/store/index";
import { Title } from "@/common/html/title";


@Component({
created: () => {
console.log("length", store.state.musicArtists.artists.length);
if (!store.state.musicArtists.artists.length) {
store.dispatch("musicArtists/getAllArtists", { root: true });
}
},
components: {
Artist,
},
computed: {
...mapState("musicArtists", ["artists"]),
count: () => {
return store.state.musicArtists.artists.length;
},
},
data: () => {
return {
store,
};
},
})
export default class Audio extends Vue {}
</script>

<style lang="scss">

</style>

此组件位于子页面上。当我导航到页面时,输出和页面最初显示没有“艺术家”,即数组为空。然后 API 调用加载“艺术家”,控制台输出验证“艺术家”已加载到状态。但是该页面不会更新新信息,无论是艺术家还是计数。 (艺术家组件只显示艺术家的名字)。

要么我在做一些非常简单和愚蠢的事情(完全有可能),要么还有其他事情???

最佳答案

我能想到的最好办法是转储 Vuex 并将代码移到类中而不是装饰器中以访问“this”。我在商店里尝试过这个,但仍然没有成功。

@Component({
components: {
Artist,
},
})
export default class Audio extends Vue {
artists:MusicArtist[];

constructor() {
super();
this.artists = [];
}

created() {
console.log("length", this.artists.length);
if (!this.artists.length) {
Providers.musicArtists.getAll(
(musicArtists: MusicArtist[]) => {
console.log("MusicArtist!", musicArtists);
this.artists = musicArtists;
},
(error: Error) => {
console.log("Error!", error);
},
);
}
}
}

关于typescript - Vuex 不更新组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52322256/

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