vuex里面的this.$store.dispatch方法

main.js
在这里插入图片描述
store/index.js
在这里插入图片描述
在store/modules文件夹里的user.js,声明user并释放出来。

const user = {
  state: {
    token: '',
    roles: null,
    isMasterAccount:true,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token ="Bearer " +token 
    },
  },
  actions: {
    // 登录
    Login({
      commit
    }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo.account, userInfo.password).then(x => {
          if(x.status==200){
            const tokenV = x.data.token.tokenValue
            commit('SET_TOKEN', tokenV)
            document.cookie=`AuthInfo=Bearer ${tokenV};path:/`;
            token="Bearer "+tokenV;
            //setToken("Bearer " +token)
            resolve();
          }
          
        }).catch(error => {
          console.log("登录失败")
          reject(error)
        })
      })
    },
  }
}

export default user

注:必须要用commit(‘SET_TOKEN’, tokenV)调用mutations里的方法,才能在store存储成功。

handleLogin() {
   this.loading = true
    this.$store.dispatch('Login', this.loginForm).then(() => {
           this.$router.push({
               path: '/manage/merchant/account'
           }); //登录成功之后重定向到首页
           this.loading = false
           // this.$router.push({ path: this.redirect || '/' })
       }).catch(() => {
           this.loading = false
       })
     }

this.$store.dispatch(‘Login’, this.loginForm)来调取store里的user.js的login方法,从而要更新。

原创文章 271 获赞 116 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_42554191/article/details/105741120