javascript - 如何等待视图组件的 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()
但不确定这是否是正确的方法。
解决方案
是的,这是正确的方法,这就是观察者的目的。
但是,如果您只能...尝试在一个组件系列中执行此类操作。(父母将道具传递给孩子,控制它);
你可以阅读这篇关于 vuex 的文章 - https://markus.oberlehner.net/blog/should-i-store-this-data-in-vuex/。它也许会澄清这个想法。只是不要将所有内容都存储在 vuex 中,因为有时它没有意义
https://vuejs.org/v2/api/#watch - 对于这个最好你应该immedaite
在观察者上使用标志并删除挂载。带有即时标志的观察者有点,观察者+立即创建
推荐阅读
- android - 在带有 Kotlin 的 Android 中使用 AutocompleteEditText 和 PlacesAutocomplete Api
- swiftui - 如何在 SwiftUI 按钮中使用布尔值?
- r - 模式匹配和替换——一个或多个相同的模式/字符
- vue.js - 渲染 HTML 中的 V-for 循环
- sql - 子查询返回多个值
- django - IntegrityError:唯一约束失败:usermanager_userprofile.email_address
- reactjs - ReactJs:如何在箭头函数中使用条件
- php - 如何在 Yii 2 中使用模型设置 Bootstrap4 ToggleButtonGroup?
- azure - 如何通过 Terraform 创建多个 VM?
- php - 为什么请求在 laravel 中不起作用,但在 pgAdmin 中起作用?