首頁  >  文章  >  web前端  >  Vuex狀態管理之Mutation的使用詳解

Vuex狀態管理之Mutation的使用詳解

藏色散人
藏色散人轉載
2022-08-10 14:47:302917瀏覽

mutations狀態更新

vuex中的store狀態更新唯一方式:提交Mutation

Mutation主要包括兩部分:

  • 字串的事件類型(type)

  • 一個回呼函數(handler),該回呼函數的第一個參數為state
    Vuex狀態管理之Mutation的使用詳解

mutations傳遞參數

在透過mutations更新資料的時候,我們可能需要攜帶一些額外的參數
參數被稱為mutations是載重(Payload)

範例:第一個按鈕點選counter 5,第二個按鈕點選counter 10

App.vue文件

<button>+5</button>
<button>+10</button>

store檔案中的index.js檔案

 mutations: {
    incrementCount(state, count) {
      state.counter += count
    }
  },

App.vue檔案

methods: {
    addCount(count) {
      this.$store.commit("incrementCount", count);
    }
  }

mutations提交風格

普通提交風格

this.$store.commit("incrementCount", count);

這樣提交,如果打印count,得到的是count

incrementCount(state, count) {
      // state.counter += count
      console.log(count);
    }

Vuex狀態管理之Mutation的使用詳解
特殊的提交風格

this.$store.commit({
        type: "incrementCount",
        count
      });

如果列印count,得到的是一個物件

    incrementCount(state, count) {
      // state.counter += count
      console.log(count);
    }

Vuex狀態管理之Mutation的使用詳解所以在mutations中這樣比較合適

incrementCount(state, payload) {
      state.counter += payload.count
      console.log(payload.count);
    }

App.vue中提交

this.$store.commit({
        type: "incrementCount",
        count
      });

mutations回應規則

vuex中的state是響應式的,當state中資料改變時,vue元件會自動更新。

當我們改變原有物件中的值時,頁面也會發生改變

state: {
    info: {
      name: 2401,
      age: 18
    }
  },
   mutations: {
    // 改变info中的值
    infoChange(state) {
      state.info.age = 10
    }
  },

在App.vue中

<h2>{{$store.state.info}}</h2>
<button>infoChange</button>
 infoChange() {
      this.$store.commit("infoChange");
    }

Vuex狀態管理之Mutation的使用詳解
Vuex狀態管理之Mutation的使用詳解
#向原有物件增加值

不能做到響應式的方法

state.info['address'] = '地球';

其實address已經被加到info中了,但是這樣的方法做不到響應式,所以在頁面上沒有顯示Vuex狀態管理之Mutation的使用詳解響應式方法

Vue.set(state.info, "address", '地球');

Vuex狀態管理之Mutation的使用詳解
刪除原有物件中的值

無法做到響應式的方法

delete state.info.age;

其實info中age已經被刪除,但這樣的方法做不到響應式,所以頁面上還存在age
Vuex狀態管理之Mutation的使用詳解
響應式方法

#
Vue.delete(state.info, "age")

Vuex狀態管理之Mutation的使用詳解

mutations常數型別

官方推薦,將mutations中的方法名稱都定義為常數,不容易出錯,也便於管理維護

在store文件下創建mutations-type.js文件,存放常數

export const INCREMENT = "increment"
export const DECREMENT = "decrement"

在store檔案下的index.js檔案中匯入並使用

import {
  INCREMENT,
  DECREMENT
} from "../store/mutations-type"
 mutations: {
    [INCREMENT](state) {
      state.counter++;
    },
    [DECREMENT](state) {
      state.counter--;
    },
  }

在App.vue檔案中匯入並使用

import { INCREMENT, DECREMENT } from "../src/store/mutations-type";
methods: {
    add() {
      this.$store.commit(INCREMENT);
    },
    sub() {
      this.$store.commit(DECREMENT);
    },
   }

【相關推薦:vue.js影片教學

以上是Vuex狀態管理之Mutation的使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除