在 uni-app 项目根目录下新建 store 目录,在 store 目录下创建 index.js 定义状态值
const store = new Vuex.Store({
state: {
login: false,
token: '',
avatarUrl: '',
userName: ''
},
mutations: {
login(state, provider) {
console.log(state)
console.log(provider)
state.login = true;
state.token = provider.token;
state.userName = provider.userName;
state.avatarUrl = provider.avatarUrl;
},
logout(state) {
state.login = false;
state.token = '';
state.userName = '';
state.avatarUrl = '';
}
}
})
然后,需要在 main.js 挂载 Vuex
import store from './store'
Vue.prototype.$store = store
最后,在 pages/index/index.vue 使用
<script>
import {
mapState,
mapMutations
} from 'vuex';
export default {
computed: {
...mapState(['avatarUrl', 'login', 'userName'])
},
methods: {
...mapMutations(['logout'])
}
}
</script>
网友评论