Vuex不更新组件

时间:2018-09-13 21:48:53

标签: typescript vue.js vuex vuex-modules

我正在用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调用以加载“艺术家”,并且控制台将验证“艺术家”是否已加载到状态。但是页面不会使用新信息(艺术家或计数)进行更新。 (“艺术家”组件仅显示艺术家的姓名。)

我正在做的事情真的很简单又愚蠢(完全可能),或者还有其他事情?

1 个答案:

答案 0 :(得分:0)

我能想到的最好的办法是转储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);
                },
            );
        }
    }
}