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);
},
}),