注意:本文使用的是 vue3.0 + vuex4.0 的写法。
一、创建一个 store 文件
import { createStore } from 'vuex';
function getUserInfo() {
return new Promise((resolve) => {
resolve({ name: '张三' })
});
}
const store = createStore({
state() {
return {
userInfo: {}
}
},
getters: {
userName(state) {
return state.userInfo.name;
}
},
mutations: {
setUserInfo(state, value) {
state.userInfo = value;
}
},
actions: {
async getUserInfo({ commit }) {
const userInfo = await getUserInfo();
commit('setUserInfo', userInfo)
}
},
});
export default store;
二、在 main.js 中引入
import { createApp } from 'vue'
import App from './App.vue'
import store from './store';
const app = createApp(App);
app.use(store);
app.mount('#app')
三、组件中使用数据
1、在 app.vue 中去调用 action 中的方法请求异步数据
<script>
import { mapActions } from 'vuex';
export default {
created() {
this.$store.dispatch('getUserInfo');
},
methods: {
...mapActions(['getUserInfo']),
}
}
</script>
2、然后在任意组件中就可以使用存储的数据了
<template>
<div>{{ userName }}</div>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
computed: {
...mapState(['userInfo']),
...mapGetters(['userName']),
},
}
</script>
|