#author("2022-12-15T10:52:39+08:00","default:Admin","Admin")
#author("2022-12-15T11:08:21+08:00","default:Admin","Admin")
[[Vue]]

&color(red){※前提条件:本文基于 Vue 2.0 创作};
#contents

* 概要 [#r6f0e489]

Vuex中store数据改变的唯一方法就是mutation

通俗理解mutations,里面装着一些改变数据方法的集合,这是Vuex设计很重要的一点,就是把处理数据逻辑方法全部放在mutations里面,使得数据和视图分离。

如何使用 mutations ?
mutation结构

每一个mutation都有一个字符串类型的事件类型(type)和回调函数(handler),也可以理解为{type:handler()} ,这和订阅发布有点类似。先注册事件,当触发响应类型的时候调用handker(),调用type的时候需要用到store.commit方法。
&color(red){Vuex 中的 mutation 非常类似于事件};:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler),也可以理解为{type:handler()}。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:这和订阅发布有点类似。先注册事件,当触发响应类型的时候调用handker(),调用type的时候需要用到store.commit方法。

#codeprettify{{
const store = new Vuex.Store({
 state: {
   count: 1
 },
 mutations: {
   //注册事件,type:increment,handler第一个参数是state;
   increment (state) {
   	 // 变更状态
  	 state.count++
   }
 }
// 页面路径:store/index.js
import { createStore } from 'vuex'
const store = createStore({
	state: {
		count: 1
	},
	mutations: {
                //注册事件,add,handler第一个参数是state;
		add(state) {
			// 变更状态
			state.count += 2
		}
	}
})
export default store

store.commit('increment')   //调用type,触发handler(state)     
}}

注意:store.commit 调用 mutation(需要在根节点注入 store)。

#codeprettify{{
<!-- 页面路径:pages/index/index.vue -->
<template>
	<view>
		<view>数量:\{\{count\}\}</view>
		<button @click="addCount">增加</button>
	</view>
</template>
<script>
import store from '@/store/index.js'
export default {
	computed: {
		count() {
			return this.$store.state.count
		}
	},
	methods: {
		addCount() {
			store.commit('add')
		}
	}
}
</script>
}}

&color(red){Mutation 必须是同步函数}; 一条重要的原则就是要记住 mutation 必须是同步函数,我们要通过提交 mutation 的方式来改变状态数据,是因为我们想要更明确地追踪到状态的变化。


* 使用 [#j2cf8cce]

** 传参 [#df0482ea]

载荷(payload)

简单理解,就是往handler(stage)中传参handler(stage,payload);一般是个对象。

&color(red){不推荐的传参方法};
#codeprettify{{
state: {
   count: 1
},
mutations: {
   increment (state, payload) {
     state.count += payload
   }
}
store.commit('increment', 10)
}}

&color(red){推荐的传参方法};
#codeprettify{{
state: {
   count: 1
},
mutations: {
   increment (state, payload) {
     state.count += payload.num
   }
}
store.commit('increment', {num:10})
}}

#hr();
コメント:
#comment_kcaptcha

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS