首页 技术 正文
技术 2022年11月15日
0 收藏 626 点赞 2,626 浏览 1321 个字

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation.Vuex 中的 mutation 非常类似于事件

每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。

这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

const store = new Vuex.Store({
state: {
count:
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
//type:increment

//提交motations:
store.commit('increment')//向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):
store.commit('increment', { amount: 10 })//对象风格的提交方式
store.commit({ type: 'increment', amount: 10 })

Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项

,提前在你的 store 中初始化好所有所需属性
,在对象上添加新属性
Vue.set(obj, 'newProp', )
//新对象替换方式
state.obj = { ...state.obj, newProp: }//mutation必须是同步函数
//任何在回调函数中进行的状态的改变都是不可追踪的。

使用常量作为mutation的事件类型

//常量放在单独的文件中
// mutation-types.jsexport const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'const store = new Vuex.Store({
state: { ... },
mutations: {
//使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
[SOME_MUTATION] (state) {
// mutate state
}
}
})

在组件中提交mutation

//可以用this.$store.commit("***");
//可以用mapMutations将组件中的 methods 映射为 store.commit 调用import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,918
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,444
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,255
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,069
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,701
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,741