• Vuex概述及核心概念


    Vuex

    概述

    Vuex是实现组件全局状态(数据)管理的一种机制,可以实现组件之间数据的共享。

    优点:

    • vuex集中管理共享的数据,易于开发和后期维护
    • 能够高效实现组件之间的数据共享,提高开发效率
    • 存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步

    基本使用

    • 安装vuex依赖包
    npm install vuex --save
    
    • 1
    • 导入vuex包
    import Vuex from vuex
    Vue.use(Vuex) 
    
    • 1
    • 2
    • 创建store对象
    const store = new Vuex.Store({
        // state中存放的就是全局共享的数据
        state: { count:0 }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 将store对象挂载到vue实例中
    new Vue({
       el: '#app',
       render: h => h(app),
       router,
       //将创建的共享数据对象,挂载到vue实例中
       //所有的组件就可以直接从store中获取全局的数据了
       store
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    核心概念

    Vuex的主要核心概念:

    State

    State提供唯一的公共数据源,所有共享的数据要统一放到Store的State中进行存储。

    const store = new Vuex.Store({
       state: { count: 0 }
    })
    
    • 1
    • 2
    • 3

    组件访问State中数据的方式:

    this.$store.state.全局数据名称
    
    //从vuex中按需导入mapState函数
    import {mapState} from 'vuex'
    //将全局数据映射为当前组件的计算属性
    computed: {
      ...mapState(['count'])
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Mutation

    Mutation用于变更Store中的数据
    只能通过mutation变更store数据,不可以直接操作store中的数据;通过这种方式虽然操作稍微繁琐一些,但是可以集中监控所有数据的变化。
    Mutation 不能执行异步操作。

    //定义Mutation
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        add(state, step) {
          //变更状态 接收参数
          state.count += step
        }
      }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    // 触发mutation时携带参数
    methods: {
      handle1() {
        this.$store.commit('add',3)
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    // 触发mutations的第一种方式
    this.$store.commit()
    
    // 第二种方式
    // 按需导入 mapMutations 函数
    import { mapMutations } from 'vuex'
    //将指定的 mutations 函数,映射为当前组件的 methods 方法
    methods: {
       ...mapMutations(['add','addN'])
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Action

    Action用于处理异步任务
    如果通过异步操作变更数据,必须通过Action,在Action中通过触发Mutation的方式间接变更数据。

    // 定义 action
    actions: {
       addNAsync(context, step) {
          setTimeout(() => {
             context.commit('addN', step)
          },1000)
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    // 触发 action 并携带参数 第一种方式
    // 调用 dispatch 函数
    this.$store.dispatch('addNAsync', 5)
    
    // 第二种触发 action 的方式
    // 导入 mapActions 函数
    import {mapActions} from 'vuex'
    //将指定的 actions 函数,映射为当前组件的 methods 函数
    methods: {
      ...mapActions(['addAsync','addNAsync'])
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    Getter

    Getter 用于对 Store 中的数据进行加工处理形成新的数据。
    Getter 可以对Store中已有的数据加工处理后形成新的数据,类似Vue的计算属性;Store中数据发生变化,Getter的数据也会跟着变化。

    // 使用getters的第一种方式
    this.$store.getters.名称
    
    // 使用getters的第二种方式
    import {mapGetters} from 'vuex'
    computed: {
       ...mapGetters(['showNum'])
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    例子

    App.vue

    <template>
      <div>
        <my-add></my-add>
        <my-sub></my-sub>
      </div>
    </template>
    
    <script>
    import add from "./components/add.vue"
    import sub from "./components/sub.vue"
    
      export default {
        data() {
          return {}
        },
        components: {
          'my-add': add,
          'my-sub': sub
        }
      }
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    main.js

    import Vue from 'vue'
    import App from './App'
    import store from './store'
    
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      store,
      components: { App },
      template: ''
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    store.js

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
        state: {
            count: 0
        },
        // 只有 mutations 中定义的函数,才有权力修改 state 中的数据
        mutations: {
            // 不要在mutations函数中执行异步操作
            add(state) {
                state.count++
            },
            addN(state,step) {
                state.count += step
            },
            sub(state) {
                state.count--
            },
            subN(state,step) {
                state.count -= step
            }
        },
        actions: {
            // context相当于new出来的实例对象
            addAsync(context) {
                setTimeout(()=> {
                    // 在 action 中,不能直接修改 state 中的数据
                    // 必须通过 context.commit() 触发某个 mutation 才行
                    context.commit('add')
                },1000)
            },
            addNAsync(context, step) {
                setTimeout(()=> {
                    context.commit('addN',step)
                },1000)
            },
            subAsync(context) {
                setTimeout(()=> {
                    context.commit('sub')
                },1000)
            },
            subNAsync(context,step) {
                setTimeout(()=> {
                    context.commit('subN',step)
                },1000)
            }
        },
        getters: {
            showNum(state) {
                return '当前最新的数量是【'+ state.count +'】'
            }
        }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

    add.vue

    <template>
        <div>
            <!-- template中this可以省略 -->
            <!-- <h3>count: {{$store.state.count}}</h3> -->
            <h3>{{$store.getters.showNum}}</h3>
            <button @click="btnHandler1">+1</button>
            <button @click="btnHandler2">+n</button>
            <button @click="btnHandler3">+1 async</button>
            <button @click="btnHandler4">+N async</button>
        </div>
    </template>
    
    <script>
    export default {
       data() {
        return {}
       },
       methods: {
        btnHandler1() {
            this.$store.commit('add')
        },
        btnHandler2() {
            // commit 调用某个 mutation 函数
            this.$store.commit('addN',3)
        },
        btnHandler3() {
            // dispatch函数专门触发action
            this.$store.dispatch('addAsync')
        },
        btnHandler4() {
            this.$store.dispatch('addNAsync', 5)
        }
       }
    }
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    sub.vue

    <template>
        <div>
            <!-- <h3>count: {{count}}</h3> -->
            <h3>{{showNum}}</h3>
            <button @click="btnHandler1">-1</button>
            <button @click="btnHandler2">-n</button>
            <button @click="subAsync">-1 async</button>
            <button @click="subNAsync(5)">-n async</button>
        </div>
    </template>
    
    <script>
    import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'
    
    export default {
       data() {
        return {}
       },
       computed: {
        // 将全局数据映射为计算属性
        ...mapState(['count']),
        ...mapGetters(['showNum'])
       },
       methods: {
        ...mapMutations(['sub','subN']),
        ...mapActions(['subAsync', 'subNAsync']),
        btnHandler1() {
            this.sub()
        },
        btnHandler2() {
            this.subN(2)
        },
       }
    }
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    效果:
    在这里插入图片描述

  • 相关阅读:
    医疗产品设计的重要性,你了解多少?
    2.2链栈
    TCP套接字【网络】
    CPP-Templates-2nd--第十九章 萃取的实现 19.1-19.3
    同城信息服务源码 本地生活服务小程序源码
    IT类课程收藏网站
    JAVASE总结作业----面向对象的三大特征
    全栈资源库【All】
    php源码 单色bmp图片取模工具 按任意方式取模 生成字节数组 自由编辑点阵
    redis的持久化
  • 原文地址:https://blog.csdn.net/m0_52942098/article/details/125975480