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)
    })
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_44582045/article/details/121852631