Vue中使用 Vuex
安装Vuex
前段代码中执行 ` npm i vuex`
配置Vuex
- 在
Client
根目录下新建store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const types = {
SET_USER:"SET_USER"//用户信息
}
const state = {
user:{}
}
const getters = {
user:state=>state.user
}
const mutations = {
[types.SET_USER](state, user) {
if (user) {
state.user = user;
} else {
state.user={}
}
}
}
const actions = {
setUser: ({ commit }, user) => {
commit(types.SET_USER,user)
}
}
export default new Vuex.Store({
state,
getters,
mutations,
actions
})
- 修改
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from "./http";
import store from "./store";
Vue.config.productionTip = false
Vue.prototype.$axios = axios
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
3.App.vue
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
import jwt_decode from "jwt-decode";
export default {
name:'app',
created(){
if(localStorage.wxpyqToken){
const decode=jwt_decode(localStorage.wxpyqToken);
this.$store.dispatch("setUser",decode)
}
}
}
</script>
<style>
html,
body,
#app {
width: 100%;
height: 100%;
}
</style>
使用Vuex
存储数据
// 存储数据
this.$store.dispatch("setUser", decode);
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭