Javascript 如何从视图组件等待Vuex状态初始化?
我正在建立一个电影网站,在VueJS上练习。在应用程序初始化过程中,我从第三方API获得了电影类型列表。由于此列表在应用程序的几个组件中都是必需的,因此我通过Vuex管理和存储它,如下所示: main.js:Javascript 如何从视图组件等待Vuex状态初始化?,javascript,vuejs2,promise,vuex,Javascript,Vuejs2,Promise,Vuex,我正在建立一个电影网站,在VueJS上练习。在应用程序初始化过程中,我从第三方API获得了电影类型列表。由于此列表在应用程序的几个组件中都是必需的,因此我通过Vuex管理和存储它,如下所示: main.js: new Vue({ router, store, vuetify, render: h => h(App), created () { this.$store.dispatch('getGenreList') } }).$mount('#app')
new Vue({
router,
store,
vuetify,
render: h => h(App),
created () {
this.$store.dispatch('getGenreList')
}
}).$mount('#app')
<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>
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:
new Vue({
router,
store,
vuetify,
render: h => h(App),
created () {
this.$store.dispatch('getGenreList')
}
}).$mount('#app')
<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>
从“vuex”导入{mapState}
从“../api/api”导入api
导出默认值{
姓名:'家',
数据(){
返回{
电影:空
}
},
计算:{
…地图状态({
部分:state=>state.genres
})
},
异步装入(){
const moviesArray=等待承诺。全部(
this.sections.map(section=>{
返回api.getMoviesByGenre(section.id)
})
)
this.movies=moviesArray
}
}
这里的问题是,在初始加载时,sections==[]
,因为尚未加载流派列表。如果我导航到另一个视图并返回,sections
会按预期保存一组类型对象
问题:我如何才能正确地等待部分加载流派?(由于没有从该组件调用getGenreList
操作,因此我无法使用该方法)
我想在部分的Watcher中实现电影列表检索,而不是在mounted()
中,但不确定这是否是正确的方法 是的,这是正确的方法,这就是观察者的目的
但是如果你能。。。尝试在一个构件族中执行类似的操作。(父母向孩子传递道具,控制道具)
您可以阅读这篇关于vuex-的文章。
这也许会澄清这个想法。只是不要将所有东西都存储在vuex中,因为有时候它“没有意义”
-对于此选项,最好在watcher上使用immdaite
标志并删除已安装的。带immedaite标志的Watcher有点像,Watcher+立即创建