如何将 api 的结果与 Vuex 的操作一起使用

How to use result of api with actions from Vuex

我正在尝试在用户登录时通过 axios 检索用户收藏夹。 为此,我将 Vuejs 与 Vuex 结合使用。关于登录过程还可以,但是关于收藏夹,我遗漏了一些东西但我不知道是什么。

我的store.ts是这样的:

export const store = createStore({
    state: {
        user: null,
        token: null,
        favorites: []
    },

    mutations: {
        setUser(state, user) {
            state.user = user;
        },
        setToken(state, token) {
            state.token = token;
        },
        setFavs(state, favorites) {
            state.favorites = favorites;
        },
    },
    actions: {
        getFavorites({ commit }) {
            axios
                .post("URL_HERE", {
                    userId: this.state.user,
                })
                .then((res) => {
                    //console.log(res);
                    commit('setFavs', res.data)

                })
                .catch((error) => {
                    console.log(error);
                })
        }
    },
    getters: {
        getFavs: (state) => state.favorites
    },
});

在我的收藏夹组件中,我有:

export default defineComponent({
  name: "Favorites",
  data() {
    return {
      favorites: null,
    };
  },
  computed: {
    ...mapGetters(["isLoggedIn"]),
    ...mapGetters({ Favorites: "getFavs" }),
  },
});

然后在模板中:

<div v-for="favorite in Favorites" :key="favorite.event_id">
 <li>{{ favorite }}</li>
</div>

您需要在挂载的钩子中调度操作:

export default defineComponent({
  name: "Favorites",
  data() {
    return {
      favorites: null,
    };
  },
  computed: {
    ...mapGetters(["isLoggedIn"]),
    ...mapGetters({ Favorites: "getFavs" }),
  },
 methods:{
  ...mapActions(['getFavorites'])//map the actions as you did with getters
 },
 mounted(){
  this.getFavorites();//dispatch the action
},
//or use a watcher
watch:{
isLoggedIn(newVal,oldVal){
  if(newVal){
        this.getFavorites()
   }
}

}
});