iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >详解vuex中的this.$store.dispatch方法
  • 421
分享到

详解vuex中的this.$store.dispatch方法

vuex中this.$store.dispatch方法vuex this.$store.dispatch 2022-11-13 19:11:48 421人浏览 安东尼
摘要

Vuex中的this.$store.dispatch方法 main.js new Vue({ el:'#app', router, store, render

Vuex中的this.$store.dispatch方法

main.js

new Vue({
   el:'#app',
   router,
   store,
   render:h=>h(APP)
 })

在这里插入图片描述

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import user from '.modules/user'
import getters from '.getters'
import permission from './modules/permission'

Vue.use(Vuex)
 const store=new Vuex.Store({
    modules:{
        permission,
	app,
	user
},
getters
})
export default store

在这里插入图片描述

在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方法,从而要更新。

vuex 中dispatch 和 commit 的用法和区别

dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)

commit:同步操作,写法:this.$store.commit('mutations方法名',值)

到此这篇关于vuex中的this.$store.dispatch方法的文章就介绍到这了,更多相关vuex中this.$store.dispatch方法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 详解vuex中的this.$store.dispatch方法

本文链接: https://www.lsjlt.com/news/170751.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作