vuex中 this.$store.dispatch() 與 this.$store.commit()方法的區(qū)別

this.store.dispatch() 與 this.store.commit()方法的區(qū)別總的來說他們只是存取方式的不同,兩個(gè)方法都是傳值給vuex的mutation改變state
this.store.dispatch() :含有異步操作,例如向后臺(tái)提交數(shù)據(jù),寫法:this.store.dispatch(‘a(chǎn)ction方法名’,值)
this.store.commit():同步操作,,寫法:this.store.commit(‘mutations方法名’,值)

commit: 同步操作

存儲(chǔ) this.store.commit('changeValue',name) 取值 this.store.state.changeValue
dispatch: 異步操作

存儲(chǔ) 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專門用來保存 共享的狀態(tài)值
  state: {
    // 保存登錄狀態(tài)
    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 {
  // 官方推薦: 給組件起個(gè)名字, 便于報(bào)錯(cuò)時(shí)的提示
  name: "Header",
  // 引入vuex 的 store 中的state值, 必須在計(jì)算屬性中書寫!
  computed: {
    // mapState輔助函數(shù), 可以快速引入store中的值
    // 此處的login代表,  store文件中的 state 中的 login, 登錄狀態(tài)
    ...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("恭喜您, 登錄成功! 即將跳轉(zhuǎn)到首頁");

            // 路由跳轉(zhuǎn)指定頁面
            this.$router.push({ path: "/" });

            //更新 vuex 的 state的值, 必須通過 mutations 提供的方法才可以
            // 通過 commit('方法名') 就可以出發(fā) mutations 中的指定方法
            this.$store.commit("doLogin");
          } else {
            alert("很遺憾, 登陸失敗!");
          }
        })
        .catch(err => {
          console.error(err);
        });
    }

  }
};
</script>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容