Vue - vuex使用

场景:vue全局获取登录用户名

一、main.js里配置安装

//安装vuex状态管理模式
import Vuex from 'vuex'
import store from './store.js'
Vue.use(Vuex)

new Vue({
  el: '#app',
  router,
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { App },
  template: '<App/>'
})

二、store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
// 这里定义初始值
let state = {
  adminName: ''
};
//更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:
// 每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。
// 这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
//需要以相应的 type 调用 store.commit 方法:你可以在组件中使用 this.$store.commit('xxx') 提交 mutation
//store.commit({
// type: 'increment',
//   amount: 10
// })对象方式提交
const mutations = {
  //登录
  login(state, name) {
    state.adminName = name;
  },
  //登出
  loginout(state) {
    state.adminName = '';
  }
};

// 事件触发后的逻辑操作
// 参数为事件函数this.$store.dispatch('login', this.user)
 dispatch采用Promise链式调用
// this.$store.dispatch('login', this.user).then(() => {
//   this.$notify({
//     type: 'success',
//     message: '欢迎你,' + this.user.name + '!',
//     duration: 3000
//   })
// computed: {  //挂载获取数据,否则不会根据store动态改变
//   user () {
//     return this.$store.state.user
//   }
const actions = {
  // 登录
  login(context, name) {
    context.commit('login',name);
  },

  // 登出
  loginout(context) {
    context.commit('loginout');
  }

};

// 返回改变后的数值
const getters = {};

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})

三、应用

登录:

 .then((res) => {
                console.log(res);
                if (res.data.code == 1) {//登陆成功
                  this.$router.push("/toMain/userInfo");//进入主页
                  this.$message({
                    message: '恭喜你,登陆成功',
                    type: 'success',
                    center: true
                  });
                  this.$store.dispatch('login', res.data.data);//状态管理
                } else {
                  this.$message.error('用户名或密码错误!');
                }
              })
 computed: {
      name() {
        return this.$store.state.adminName;
      }
    }
<span>当前用户:{{name}}</span>

退出登录:

 loginout() {
        this.$http.get(this.loginOutUrl).then((res) => {
          console.log(res);
          if (res.data.code == 1) {
            this.$store.dispatch('loginout');//状态管理
            this.$router.push('/');
          } else {
            this.$message.error("退出登录失败")
          }
        })
      }

四、资料参考

https://blog.csdn.net/TONELESS/article/details/71638369

https://www.cnblogs.com/yesyes/p/6659292.html

https://www.cnblogs.com/DM428/p/7293867.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孟林洁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值