vue全局参数
作者:互联网
文章目录
全局参数
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m3T6uPFB-1633493673147)(C:\Users\HeShuo\AppData\Roaming\Typora\typora-user-images\image-20210929182907244.png)]
一定要记得
main.js
中添加store写成形式一:(放弃形式二)
形式一
import Vue from "vue";
import Vuex from 'vuex'
Vue.use(Vuex)
const stores = new Vuex.Store({
state: {
token: localStorage.getItem("token"),
userInfo: JSON.parse(sessionStorage.getItem("userInfo"))
},
mutations: {
SET_TOKEN: (state,token) =>{
state.token = token
localStorage.setItem("token",token)
},
SET_USERINFO: (state,userInfo) =>{
state.userInfo = userInfo
sessionStorage.setItem("token",JSON.stringify(userInfo))
},
REMOVE_INFO: (state) => {
state.token = ''
state.userInfo = {}
localStorage.setItem("token",'')
sessionStorage.setItem("userInfo",JSON.stringify(''))
}
},
getters: {
getUser: state => {
return state.userInfo
},
getToken: state => {
return state.token
}
//其他地方也可以直接 state.token
},
actions: {
},
modules: {
}
})
export default stores
main.js
import Vue from 'vue'
import App from './App.vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
import gg from "@/router";
import stores from "@/store";
Vue.use(ElementUI);
Vue.prototype.$axios = axios
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router: gg,
store: stores
}).$mount('#app')
不添加的话,_this
这里会报错
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WYRYsqd7-1633493673153)(C:\Users\HeShuo\AppData\Roaming\Typora\typora-user-images\image-20210929192846806.png)]
形式二
import Vue from "vue";
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
token: '',
//userInfo: {}
userInfo: JSON.parse(sessionStorage.getItem("userInfo")) //初始化时直接从sessionStore获取,反序列,上同
},
mutations: {
// set方法
SET_TOKEN: (state,token) =>{
state.token = token
localStorage.setItem("token",token) //存储
},
SET_USERINFO: (state,userInfo) =>{
state.userInfo = userInfo
sessionStorage.setItem("token",JSON.stringify(userInfo))
},
REMOVE_INFO: (state) => {
state.token = ''
state.userInfo = {} //userInfo 是一个对象
localStorage.setItem("token",'')
sessionStorage.setItem("userInfo",JSON.stringify('')) //只能存储字符串,所以要对对象进行序列化
}
},
getters: {
//get方法
getUser: state => {
return state.userInfo
}
//其他地方也可以直接 state.token
},
actions: {
},
modules: {
}
})
标签:vue,token,setItem,state,Vue,参数,userInfo,import,全局 来源: https://blog.csdn.net/qq_34449634/article/details/120623335