首页 > 解决方案 > 如何等待视图组件的 Vuex 状态初始化?

问题描述

我正在建立一个电影网站来练习 VueJS。在应用程序初始化期间,我从 3rd-party API 获取电影类型列表。由于应用程序的多个组件都需要此列表,因此我通过 Vuex 管理和存储它,如下所示:

主.js:

new Vue({
  router,
  store,
  vuetify,
  render: h => h(App),
  created () {
    this.$store.dispatch('getGenreList')
  }
}).$mount('#app')

Vuex 的index.js

export default new Vuex.Store({
  state: {
    genres: []
  },
  mutations: {
    setGenreList (state, payload) {
      state.genres = payload
    }
  },
  actions: {
    async getGenreList ({ commit }) {
      try {
        const response = await api.getGenreList() // axios call defined in api.js
        commit('setGenreList', response)
      } catch (error) {
        console.log(error)
      }
    }
  }
})

现在,在我的主页视图中,我想检索每种类型的电影列表,如下所示:

主页.vue:

<script>
import { mapState } from 'vuex'
import api from '../api/api'

export default {
  name: 'home',
  data () {
    return {
      movies: null
    }
  },
  computed: {
    ...mapState({
      sections: state => state.genres
    })
  },
  async mounted () {
    const moviesArray = await Promise.all(
      this.sections.map(section => {
        return api.getMoviesByGenre(section.id)
      })
    )
    this.movies = moviesArray
  }

}
</script>

这里的问题是,在初始加载时,sections===[]由于尚未加载流派列表。如果我导航到另一个视图并返回,sections则按预期保存一系列流派对象。

问题:如何正确等待sections加载流派?(由于getGenreList没有从该组件调用该操作,因此我无法使用方法)

我正在考虑在 Watcher 中sections而不是在中实现电影列表检索,mounted()但不确定这是否是正确的方法。

标签: javascriptvuejs2promisevuex

解决方案


是的,这是正确的方法,这就是观察者的目的。

但是,如果您只能...尝试在一个组件系列中执行此类操作。(父母将道具传递给孩子,控制它);

你可以阅读这篇关于 vuex 的文章 - https://markus.oberlehner.net/blog/should-i-store-this-data-in-vuex/。它也许会澄清这个想法。只是不要将所有内容都存储在 vuex 中,因为有时它没有意义

https://vuejs.org/v2/api/#watch - 对于这个最好你应该immedaite在观察者上使用标志并删除挂载。带有即时标志的观察者有点,观察者+立即创建


推荐阅读