官方建议在store文件夹,里面的index.js,定义修改公共变量的公共方法,这样其他组件直接调用方法。

如果只是简单的同步方法,组件里面可以直接使用这个函数,不一定要通过actions来使用

好处是通过官方的浏览器插件Devtools,可以查看到哪个地方修改的值,避免一堆组件都可以改,都不知道谁改的

定义

vuex 3 和 vue2

src/store/index.js

  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. Vue.use(Vuex)
  4. export default new Vuex.Store({
  5. state: {
  6. share:100
  7. },
  8. mutations: {
  9. //定义修改的方法,自带参数start,相当于就是这个store对象
  10. addShare:function(state){
  11. state.share++;
  12. }
  13. },
  14. actions: {
  15. },
  16. modules: {
  17. }
  18. })

vuex 4 和 vue3

src/store/index.js
image.png
加上外部的参数:
image.png

参数是对象:
image.png

使用

模板上使用

组件内,在模板template上可以这样使用
image.png

vuex 3 和 vue2、vue3选项api

组件内,通过选项API,用 this.$store.commit( )方法调用修改变量的方法

  1. <template>
  2. <div>
  3. test2
  4. <el-button @click="add">add</el-button>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. data() {
  10. return {
  11. };
  12. },
  13. methods: {
  14. add:function () {
  15. // 1、简单提交
  16. //this.$store.commit( "函数名A" , 单个参数 )
  17. // 或
  18. //this.$store.commit( "函数名A" , { 多个参数用参数对象} ) 推荐
  19. this.$store.commit("addShare")
  20. // 2、参数是对象
  21. /*
  22. this.$store.commit({
  23. type:"函数名A",
  24. 参数A :参数A的值,
  25. ...
  26. 参数N : 参数N的值
  27. })
  28. */
  29. this.$store.commit({
  30. type:"addShare",
  31. a:"aa",
  32. b:"bb"
  33. })
  34. }
  35. },
  36. };
  37. </script>
  38. <style scoped>
  39. </style>

vue 3 组合api 简单使用

  1. <template>
  2. <div>
  3. test2
  4. <el-button @click="add">add</el-button>
  5. </div>
  6. </template>
  7. <script>
  8. import {useStore} from 'vuex'
  9. export default {
  10. setup(){
  11. const store = useStore()
  12. const add = ()=>{
  13. // 参数用法和上面选项api一样
  14. store.commit("addShare")
  15. }
  16. return {
  17. add
  18. }
  19. }
  20. };
  21. </script>
  22. <style scoped>
  23. </style>

批量使用 mapMutations

参考mapState和mapGetters的简单使用

  1. <template>
  2. <div>
  3. <h2>当前计数: {{ $store.state.counter }}</h2>
  4. <hr>
  5. <button @click="increment">+1</button>
  6. <button @click="add">+1</button>
  7. <button @click="decrement">-1</button>
  8. <hr>
  9. </div>
  10. </template>
  11. <script>
  12. import { mapMutations, mapState } from 'vuex'
  13. export default {
  14. // 选项api
  15. methods: {
  16. ...mapMutations(["increment", "decrement"]),
  17. ...mapMutations({
  18. add: "increment"
  19. })
  20. },
  21. // 组合api
  22. setup() {
  23. const storeMutations = mapMutations(["increment", "decrement"])
  24. return {
  25. ...storeMutations
  26. }
  27. }
  28. }
  29. </script>
  30. <style scoped>
  31. </style>

注意

1、mutations 内的必须是同步函数
2、也可以通过引入常量的方式决定函数名,避免写错也方便后面修改(非必要)
image.png
3、工具可以查看到修改的历史,以及值,可以一步一步调试

Devtools

正确使用就会正常记录到devtools里面
image.png