国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vuex之理解Mutations的用法實例

2024-05-06 15:18:20
字體:
來源:轉載
供稿:網友

1.什么是mutations?

上一篇文章說的getters是為了初步獲取和簡單處理state里面的數據(這里的簡單處理不能改變state里面的數據),Vue的視圖是由數據驅動的,也就是說state里面的數據是動態變化的,那么怎么改變呢,切記在Vuexstore數據改變的唯一方法就是mutation

通俗的理解mutations,里面裝著一些改變數據方法的集合,這是Veux設計很重要的一點,就是把處理數據邏輯方法全部放在mutations里面,使得數據和視圖分離。

2.怎么用mutations?

mutation結構:每一個mutation都有一個字符串類型的事件類型(type)和回調函數(handler),也可以理解為{type:handler()},這和訂閱發布有點類似。先注冊事件,當觸發響應類型的時候調用handker(),調用type的時候需要用到store.commit方法。

const store = new Vuex.Store({  state: {    count: 1    },  mutations: {  increment (state) {   //注冊時間,type:increment,handler第一個參數是state;     // 變更狀態    state.count++}}})      store.commit('increment')  //調用type,觸發handler(state)   

載荷(payload):簡單的理解就是往handler(stage)中傳參handler(stage,pryload);一般是個對象。

 mutations: { increment (state, n) {   state.count += n}} store.commit('increment', 10)mutation-types:將常量放在單獨的文件中,方便協作開發。  // mutation-types.js export const SOME_MUTATION = 'SOME_MUTATION'  // store.jsimport Vuex from 'vuex'import { SOME_MUTATION } from './mutation-types' const store = new Vuex.Store({  state: { ... },  mutations: {   // 我們可以使用 ES2015 風格的計算屬性命名功能來使用一個常量作為函數名  [SOME_MUTATION] (state) {  // mutate state }}})

commit:提交可以在組件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 輔助函數將組件中的 methods 映射為 store.commit 調用(需要在根節點注入 store)。

import { mapMutations } from 'vuex'export default {methods: { ...mapMutations([  'increment' // 映射 this.increment() 為 this.$store.commit('increment')]), ...mapMutations({  add: 'increment' // 映射 this.add() 為 this.$store.commit('increment') })}}

3.源碼分析

registerMutation:初始化mutation

function registerMutation (store, type, handler, path = []) { //4個參數,store是Store實例,type為mutation的type,handler,path為當前模塊路徑  const entry = store._mutations[type] || (store._mutations[type] = []) //通過type拿到對應的mutation對象數組   entry.push(function wrappedMutationHandler (payload) {   //將mutation包裝成函數push到數組中,同時添加載荷payload參數     handler(getNestedState(store.state, path), payload)   //通過getNestedState()得到當前的state,同時添加載荷payload參數  }) }            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 天镇县| 莱芜市| 花莲县| 吴堡县| 故城县| 丽江市| 新乡市| 开远市| 顺昌县| 曲阳县| 酉阳| 乌拉特后旗| 扎兰屯市| 商河县| 松溪县| 安新县| 鹤峰县| 星子县| 虹口区| 喀什市| 灵山县| 任丘市| 乐业县| 澎湖县| 广饶县| 婺源县| 武山县| 小金县| 饶河县| 永嘉县| 临沭县| 松桃| 红原县| 石台县| 邢台县| 吴川市| 安西县| 陵川县| 张家川| 观塘区| 库尔勒市|