3

我正在用 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 调用加载“艺术家”,控制台输出验证“艺术家”是否已加载到状态。但是该页面不会更新新信息,无论是艺术家还是计数。(艺术家组件只显示艺术家的名字)。

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

4

1 回答 1

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);
                },
            );
        }
    }
}
于 2018-09-14T03:42:08.477 回答