vuex的使用
用户登录存储用户信息在子页面获取对应的用户信息配合vuex的使用
- npm install vuex --save
下载vuex,会有一个store的文件
Vue.use(Vuex)引用vuex并将store暴露出去
import Vue from ‘vue’
import Vuex from ‘vuex’
Vue.use(Vuex)
const store = new Vuex.Store({
})
export default store
-
一般登录时候会需要将用户信息保存下来,在main.js内引用store
import store from ‘./store’
new Vue({
el: ‘#app’,
store,
render: h => h(App)
}) -
在login页面保存用户信息
this.$store.commit(“username”, username);
this.$store.commit(“password”, password);
-
在store.getters.js内
const getters = {
//password: state => state.password, //aid:state => state.username, getPassword:function(state){ return state.password }, getUsername:function(state){ return state.username }, } export default getters
注释的是另一种写法
-
在store.index.js里面
import getters from ‘./getters’
const store = new Vuex.Store({
state:{
password:sessionStorage.getItem(“password”),
//声明一个password变量在session中 get获取;
username: sessionStorage.getItem(‘username’)
},
mutations:{
password(state,n){
state.password=n
sessionStorage.setItem(“password”, n)
//password是方法名/state是当前state对象,n是传入的形参
},
username(state,n){
state.username=n
sessionStorage.setItem(‘username’, n)
}
},modules: {
app,
user
},
getters
}) -
this.username= this.$store.getters.getUsername;
在对应的页面内获取你需要的用户信息