【问题标题】:How to wait on Vuex state initialization from a view component?如何等待视图组件的 Vuex 状态初始化?
【发布时间】:2020-06-21 08:59:47
【问题描述】:

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

ma​​in.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)
      }
    }
  }
})

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

Home.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 操作,我不能使用this 方法)

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

【问题讨论】:

    标签: javascript vuejs2 promise vuex


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 1970-01-01
      • 2019-11-11
      • 2019-10-30
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      相关资源
      最近更新 更多