文章目录
一、mutations介绍
通过
mutations
来修改状态相关的数据
Vuex的
store
状态的更新唯一方式 : 提交Mutation
二、mutations的基本使用
import Vue from 'vue'
import Vuex from 'vuex'
// 1. 安装插件
Vue.use(Vuex)
// 2. 创建对象
const store = new Vuex.Store({
// 存放状态相关的数据
state: {
counter: 0
},
// 通过mutations修改状态相关的数据
mutations: {
// 方法, 默认有一个state参数
increment(state) {
state.counter++
},
decrement(state) {
state.counter--
}
}
})
// 3. 导出
export default store
上述代码在mutations里面增加了两个方法, 用来增加和减小state里面的counter变量
2.1 使用commit访问mutations里面定义的方法
<template>
<div id="app">
<home></home>
<!-- 修改vuex里面的数据 -->
<button @click="add">+</button>
<button @click="sub">-</button>
</div>
</template>
<script>
import Home from './components/Home.vue'
export default {
name: 'App',
components: {
Home
},
methods: {
add() {
// 使用mutations里面定义的increment方法
this.$store.commit("increment")
},
sub() {
this.$store.commit("decrement")
}
},
}
</script>
<style>
</style>
三、使用devtools插件监听mutations的操作
四、Mutation主要包括两部分
1 . 字符串的事件类型
2. 一个回调函数, 该回调函数的第一个参数就是state
五、mutations携带参数
在通过mutation更新数据的时候, 有可能我们希望携带一些额外的参数
参数被称为是mutation的载荷(Payload).
index.js
import Vue from 'vue'
import Vuex from 'vuex'
// 1. 安装插件
Vue.use(Vuex)
// 2. 创建对象
const store = new Vuex.Store({
// 存放状态相关的数据
state: {
counter: 100,
},
// 通过mutations修改状态相关的数据
mutations: {
// 定义一个参数, 让使用者传递
increCounter(state, coun) {
state.counter += coun
}
}
})
// 3. 导出
export default store
App.vue
<template>
<div id="app">
<h2>{{this.$store.state.counter}}</h2>
<button @click="addCounter(5)">+5</button>
</div>
</template>
<script>
import Home from './components/Home.vue'
export default {
name: 'App',
components: {
Home
},
methods: {
// 定义一个方法, 并传递数据
addCounter(counter) {
// 调用store的increCounter方法, 并传递数据
this.$store.commit("increCounter", counter)
}
},
}
</script>
<style>
</style>
六、mutations的类型常量
为防止类型名字写错, 可以把类型名字抽在一个文件里面, 每次需要的时候再导入
6.1 抽取
mutations-type.js
export const INCREMENT = 'increment'
6.2 使用
index.js
import {INCREMENT} from './mutations-type'
// 2. 创建对象
const store = new Vuex.Store({
// 存放状态相关的数据
state: {
counter: 100,
},
// 通过mutations修改状态相关的数据
mutations: {
// 方法, 默认有一个state参数
[INCREMENT](state) {
state.counter++
}
},
})
App.vue
<script>
import {INCREMENT} from './store/mutations-type'
export default {
name: 'App',
components: {
Home
},
methods: {
add() {
// 使用mutations里面定义的increment方法
this.$store.commit(INCREMENT)
}
},
}
</script>
<style>
</style>
七、如果在mutaions添加数据, 是做不到响应式的
当给state中的对象添加新属性时, 可以使用
Vue.set(obj, 'newProp', 123)
import Vue from 'vue'
export default {
updateInfo(state) {
Vue.set(state.info, 'address', '中')
}
}