官方建议在store文件夹,里面的index.js,定义修改公共变量的公共方法,这样其他组件直接调用方法。
如果只是简单的同步方法,组件里面可以直接使用这个函数,不一定要通过actions来使用
好处是通过官方的浏览器插件Devtools,可以查看到哪个地方修改的值,避免一堆组件都可以改,都不知道谁改的
定义
vuex 3 和 vue2
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
share:100
},
mutations: {
//定义修改的方法,自带参数start,相当于就是这个store对象
addShare:function(state){
state.share++;
}
},
actions: {
},
modules: {
}
})
vuex 4 和 vue3
src/store/index.js
加上外部的参数:
参数是对象:
使用
模板上使用
vuex 3 和 vue2、vue3选项api
组件内,通过选项API,用 this.$store.commit( )方法调用修改变量的方法
<template>
<div>
test2
<el-button @click="add">add</el-button>
</div>
</template>
<script>
export default {
data() {
return {
};
},
methods: {
add:function () {
// 1、简单提交
//this.$store.commit( "函数名A" , 单个参数 )
// 或
//this.$store.commit( "函数名A" , { 多个参数用参数对象} ) 推荐
this.$store.commit("addShare")
// 2、参数是对象
/*
this.$store.commit({
type:"函数名A",
参数A :参数A的值,
...
参数N : 参数N的值
})
*/
this.$store.commit({
type:"addShare",
a:"aa",
b:"bb"
})
}
},
};
</script>
<style scoped>
</style>
vue 3 组合api 简单使用
<template>
<div>
test2
<el-button @click="add">add</el-button>
</div>
</template>
<script>
import {useStore} from 'vuex'
export default {
setup(){
const store = useStore()
const add = ()=>{
// 参数用法和上面选项api一样
store.commit("addShare")
}
return {
add
}
}
};
</script>
<style scoped>
</style>
批量使用 mapMutations
参考mapState和mapGetters的简单使用
<template>
<div>
<h2>当前计数: {{ $store.state.counter }}</h2>
<hr>
<button @click="increment">+1</button>
<button @click="add">+1</button>
<button @click="decrement">-1</button>
<hr>
</div>
</template>
<script>
import { mapMutations, mapState } from 'vuex'
export default {
// 选项api
methods: {
...mapMutations(["increment", "decrement"]),
...mapMutations({
add: "increment"
})
},
// 组合api
setup() {
const storeMutations = mapMutations(["increment", "decrement"])
return {
...storeMutations
}
}
}
</script>
<style scoped>
</style>
注意
1、mutations 内的必须是同步函数
2、也可以通过引入常量的方式决定函数名,避免写错也方便后面修改(非必要)
3、工具可以查看到修改的历史,以及值,可以一步一步调试
Devtools
正确使用就会正常记录到devtools里面