前言
Vuex笔记-state与mutations的使用
一、state
1、Vuex使用单一状态树,即每个项目仅包含一个store实例
2、子模块将放置在store实例的modules中
3、state的使用方式类似vue实例中的data,例如:
// store/index.js
const state = {
counter: 0,
students: [
{id: 110, name: 'Elsa', age: 18},
{id: 111, name: 'Anna', age: 17},
{id: 112, name: 'John', age: 30},
{id: 113, name: 'Olaf', age: 6},
]
}
const store = new Vuex.Store({
state,
mutations: {}
})
二、mutations
1、更改Vuex中store实例的state的方法是提交mutation
2、mutations的使用方法类似于vue实例的methods
3、mutations中的函数默认第一个参数为state
4、使用this.$store.commit()对mutaions函数进行提交
注:mutations中的函数必须是同步的,异步函数在actions中实现
图片来源:https://vuex.vuejs.org/zh/
二、实际代码
1.新建mutations.js
mutations代码如下:
export default {
// 默认第一个参数为state
increment(state) {
state.counter++
},
decrement(state) {
state.counter--
},
decrementCount(state, payload) {
// 1.普通提交的接收参数
state.counter -= payload
console.log('decrementCount打印的payload = ', payload);
},
incrementCount(state, payload) {
// 2.特殊提交的接收参数
state.counter += payload.count
console.log('incrementCount打印的payload = ', payload);
}
}
2.store/index.js中导入mutations
store/index.js代码如下:
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from "@/store/mutations";
// 1.安装插件
Vue.use(Vuex)
// 2.创建对象
const state = {
counter: 0,
students: [
{id: 110, name: 'Elsa', age: 18},
{id: 111, name: 'Anna', age: 17},
{id: 112, name: 'John', age: 30},
{id: 113, name: 'Olaf', age: 6},
]
}
const store = new Vuex.Store({
state,
mutations
})
// 3.导出store对象
export default store
3.App.vue
App.vue代码如下:
<template>
<div>
<h2>counter = {{$store.state.counter}}</h2>
<button @click="add">+</button>
<button @click="sub">-</button>
<button @click="addCount(10)">+10</button>
<button @click="subCount(10)">-10</button>
</div>
</template>
<script>
export default {
name: 'App',
methods: {
add() {
this.$store.commit('increment')
},
sub() {
this.$store.commit('decrement')
},
subCount(count) {
// 1.普通的提交封装
this.$store.commit('decrementCount', count)
},
addCount(count) {
// 2.特殊的提交封装
this.$store.commit({
type: 'incrementCount',
count
})
}
}
}
</script>
<style>
</style>
三、演示效果
总结
Vuex笔记-state与mutations的使用