1、在需要使用数据的组件中的mounted方法中,调用dispatch()方法,括号内指定的是actions中的定义的。
<script>
export default {
mounted() {
this.$store.dispatch("doActions");
},
};
</script>
2、actions中的doActions是一个异步方法,等待reqCategoryList()方法返回请求结果,把结果通过commit提交给mutations处理。
const actions = {
async doActions({ commit }) {
const result = await reqCategoryList();
commit('doMutation', result.data);
}
}
3、mutations对state进行修改。把 state.logindata的值修改为请求回来的数据。
const mutations = {
doMutation(state, data) {
state.logindata = data;
}
}
4、state中存储这logindata这个数据。
const state = {
logindata: []
}
5、在需要数据的组件使用,使用vuex的mapState方法,给组件的计算属性加上一个方法categoryList,这个方法返回的就是存储在state中的数据。
computed: {
...mapState({
categoryList: (state) => {
return state.home.categoryList;
// console.log(state);
},
}),
文章介绍了如何在Vue.js应用中使用Vuex进行状态管理,包括在组件mounted时通过dispatch调用actions,异步的doActions等待reqCategoryList请求结果后通过commit传递给mutations进行数据更新,以及在组件中使用mapState获取state中的数据。
1036

被折叠的 条评论
为什么被折叠?



