欢迎收看陈某人的博客,对于vue-admin-template进阶过程(二)

vuex的使用

用户登录存储用户信息在子页面获取对应的用户信息配合vuex的使用

  1. 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
  1. 一般登录时候会需要将用户信息保存下来,在main.js内引用store

    import store from ‘./store’
    new Vue({
    el: ‘#app’,
    store,
    render: h => h(App)
    })

  2. 在login页面保存用户信息

    this.$store.commit(“username”, username);

    this.$store.commit(“password”, password);

  3. 在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
    

注释的是另一种写法

  1. 在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
    })

  2. this.username= this.$store.getters.getUsername;
    在对应的页面内获取你需要的用户信息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值