1. 程式人生 > 其它 >[轉]vuex中 this.$store.dispatch() 與 this.$store.commit()方法的區別

[轉]vuex中 this.$store.dispatch() 與 this.$store.commit()方法的區別

this.$store.dispatch()this.$store.commit()方法的區別總的來說他們只是存取方式的不同,兩個方法都是傳值給vuex的mutation改變state
this.$store.dispatch() :含有非同步操作,例如向後臺提交資料,寫法:this.$store.dispatch('action方法名',值)

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

commit: 同步操作

儲存 this.$store.commit('changeValue',name)
取值 this.$store.state.changeValue


dispatch: 非同步操作

儲存 this.$store.dispatch('getlists',name)
取值 this.$store.getters.getlists
案例 :

Vuex檔案 src/store/index.js

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

元件JS部分 : src/components/Header.vue

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

元件JS部分 : src/components/Login.vue

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

原文連結:https://blog.csdn.net/qq_44317018/article/details/105784086