vuex中this.$store.commit和this.$store.dispatch的基本用法实例

目录
  • 前言
  • 区别
  • 实战
  • 总结

前言

this. s t o r e . d i s p a t c h ( ) 与 t h i s . store.dispatch() 与 this. store.dispatch()与this.store.commit()方法的区别总的来说他们只是存取方式的不同,两个方法都是传值给vuex的mutation改变state

区别

  • this.$store.commit()

同步操作

this.$store.commit('方法名',值)【存储】

this.$store.state.方法名【取值】
  • this.$store.dispatch()

异步操作

this.$store.dispatch('方法名',值)【存储】

this.$store.getters.方法名【取值】

当操作行为中含有异步操作:

比如向后台发送请求获取数据,就需要使用action的dispatch去完成了。

其他使用commit即可。

commit => mutations,用来触发同步操作的方法。

dispatch =>actions,用来触发异步操作的方法。

在store中注册了mutation和action,在组件中用dispatch调用action,然后action用commit调用mutation。

实战

  • this.$store.commit()
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export const store = new Vuex.Store({
  // state专门用来保存 共享的状态值
  state: {
    // 保存登录状态
    login: false
  },
  // mutations: 专门书写方法,用来更新 state 中的值
  mutations: {
    // 登录
    doLogin(state) {
      state.login = true;
    },
    // 退出
    doLogout(state) {
      state.login = false;
    }
  }
});
<script>
// 使用vux的 mapState需要引入
import { mapState } from "vuex";

export default {
  // 官方推荐: 给组件起个名字, 便于报错时的提示
  name: "Header",
  // 引入vuex 的 store 中的state值, 必须在计算属性中书写!
  computed: {
    // mapState辅助函数, 可以快速引入store中的值
    // 此处的login代表,  store文件中的 state 中的 login, 登录状态
    ...mapState(["login"])
  },
  methods: {
    logout() {
      this.$store.commit("doLogout");
    }
  }
};
</script>

<script>
export default {
  name: "Login",
  data() {
    return {
      uname: "",
      upwd: ""
    };
  },
  methods: {
    doLogin() {
      console.log(this.uname, this.upwd);
      let data={
        uname:this.uname,
        upwd:this.upwd
      }
       this.axios
        .post("user_login.php", data)
        .then(res => {
          console.log(res);
          let code = res.data.code;

          if (code == 1) {
            alert("恭喜您, 登录成功! 即将跳转到首页");

            // 路由跳转指定页面
            this.$router.push({ path: "/" });

            //更新 vuex 的 state的值, 必须通过 mutations 提供的方法才可以
            // 通过 commit('方法名') 就可以出发 mutations 中的指定方法
            this.$store.commit("doLogin");
          } else {
            alert("很遗憾, 登陆失败!");
          }
        })
        .catch(err => {
          console.error(err);
        });
    }

  }
};
</script>
  • this.$store.dispatch()
toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    }
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}
const actions = {
  // user login
  login({ commit }, userInfo){
    const { username, password,useraccount} = userInfo;
    return new Promise((resolve, reject) => {
      login(({userName:username,userAccount:useraccount,userPassword:password})).then(response=>{
        const data=response;
        commit('SET_TOKEN', 1)
        setToken(null)
        commit('SET_ROLES', 1)
        commit('SET_NAME', 1)
        commit('SET_AVATAR', 1)
        commit('SET_INTRODUCTION', 1)
        resolve()
      }).catch(error => {
       reject(error)
      //  debugger;
        //  $Message("密码或账号不对")
     })
    }).catch(error => {
      reject(error)
    })
  }
}

总结

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

(0)

相关推荐

  • vuex中store.commit和store.dispatch的区别及使用方法

    目录 store.commit和store.dispatch的区别及使用 规范的使用方式 主要区别 this.$store.dispatch() 与 this.$store.commit() 总结 store.commit和store.dispatch的区别及使用 代码示例: this.$store.commit('loginStatus', 1); this.$store.dispatch('isLogin', true); 规范的使用方式 // 以载荷形式 store.commit('inc

  • vue3中router路由以及vuex的store使用解析

    目录 vue3 router路由及vuex store使用 1.路由 2.vuex vue3中router路由和vuex的store使用,获取对象基本使用 vue3中router和store使用方法 1.企业开发Router全局配置 2.企业开发Store全局配置 功能快捷键 vue3 router路由及vuex store使用 1.路由 <script> import { useRouter, useRoute } from 'vue-router' export default {   s

  • vue在.js文件中引入store和router问题

    目录 在.js文件中引入store和router 在js文件中使用vue的router和store 总结 在.js文件中引入store和router 在js文件中使用vue的router和store 在js文件中引入vue的路由配置文件 或者 store文件 import store from '../store'; import router from '../router'; //直接使用即可 router.push({'path': '/'}) store.state.XXX;  总结 以

  • Vuex中this.$store.commit()和this.$store.dispatch()区别说明

    目录 this.$store.commit()和this.$store.dispatch()的区别 commit: 同步操作 dispatch: 异步操作 其他了解 Vuex应用实例this.$store.commit()触发 新建文件夹store,store下 头部公共组件components文件夹下 this.$store.commit()和this.$store.dispatch()的区别 两个方法其实很相似,关键在于一个是同步,一个是异步 commit: 同步操作 this.$store

  • vuex中this.$store.commit和this.$store.dispatch的基本用法实例

    目录 前言 区别 实战 总结 前言 this. s t o r e . d i s p a t c h ( ) 与 t h i s . store.dispatch() 与 this. store.dispatch()与this.store.commit()方法的区别总的来说他们只是存取方式的不同,两个方法都是传值给vuex的mutation改变state 区别 this.$store.commit() 同步操作 this.$store.commit('方法名',值)[存储] this.$sto

  • C#中Predicate<T>与Func<T, bool>泛型委托的用法实例

    本文以实例形式分析了C#中Predicate<T>与Func<T, bool>泛型委托的用法,分享给大家供大家参考之用.具体如下: 先来看看下面的例子: static void Main(string[] args) { List<string> l = new List<string>(); l.Add("a"); l.Add("b"); l.Add("s"); l.Add("t&quo

  • Vuex中mutations和actions的区别及说明

    目录 mutation Mutation 必须是同步函数 Action 在实际开发的store文件中 总结 mutation 我们知道,在使用vuex对项目状态进行管理时,只能使用commit来提交mutation对store中的状态进行更改 Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler).这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数: const

  • vuex中store存储store.commit和store.dispatch的用法

    代码示例: this.$store.commit('loginStatus', 1); this.$store.dispatch('isLogin', true); 规范的使用方式: // 以载荷形式 store.commit('increment',{ amount: 10 //这是额外的参数 }) // 或者使用对象风格的提交方式 store.commit({ type: 'increment', amount: 10 //这是额外的参数 }) 主要区别: dispatch:含有异步操作,数

  • 浅谈Vuex的this.$store.commit和在Vue项目中引用公共方法

    1.在Vue项目中引用公共方法 作为一个新人小白,在使用vue的过程中,难免会遇到很多的问题,比如某个方法在很多组件中都能用的上,如果在每个组件上都去引用一次的话,会比较麻烦,增加代码量.怎么做比较好呢,话不多说直接看代码把 首先 要在main.js中引入公共js.然后,将方法赋在Vue的原型链上. 像图中这样. 然后在需要的组件上去引入这个方法 mouted (){ //调用方法 this.common.login(); } /**然后公共方法里写一段简单的代码*/ export defaul

  • vuex中store存储store.commit和store.dispatch的区别及说明

    目录 store存储store.commit和store.dispatch区别 主要区别 vuex store原理及使用指南 使用 安装 示例需求场景 源码目录结构 store组件初始化 store存储store.commit和store.dispatch区别 代码示例: this.$store.commit('loginStatus', 1); this.$store.dispatch('isLogin', true); 规范的使用方式: // 以载荷形式 store.commit('incr

  • vuex 解决报错this.$store.commit is not a function的方法

    Vue的项目中,如果项目简单, 父子组件之间的数据传递可以使用 props 或者 $emit 等方式 进行传递 但是如果是大中型项目中,很多时候都需要在不相关的平行组件之间传递数据,并且很多数据需要多个组件循环使用.这时候再使用上面的方法会让项目代码变得冗长,并且不利于组件的复用,提高了耦合度. Vue 的状态管理工具 Vuex 完美的解决了这个问题. 看了下vuex的官网,觉得不是很好理解,有的时候我们只是需要动态的从一个组件中获取数据(官网称为"组件层级":是个独立的控件,作用范围

  • vue.js的状态管理vuex中store的使用详解

    一.状态管理(vuex)简介 vuex是专为vue.js应用程序开发的状态管理模式.它采用集中存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化.vuex也集成刀vue的官方调试工具devtools extension,提供了诸如零配置的time-travel调试.状态快照导入导出等高级调试功能. 二.状态管理核心 状态管理有5个核心,分别是state.getter.mutation.action以及module.分别简单的介绍一下它们: 1.state state为

随机推荐