zoukankan      html  css  js  c++  java
  • Vuex使用

    一、Vuex 概述

    1.1 Vue中组件之间共享数据的方式(小范围)

    1、父向子传值:v-bind 属性绑定
    2、子向父传值:v-on 时间绑定
    3、兄弟组件之间共享数据: EventBus

    • $on 接收数据的那个组件
    • $emit 发送数据的那个组件

    1.2 Vuex概述

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

    • 使用Vuex统一管理状态的好处
      ①能够在vuex中集中管理共享的数据,易于开发和后期维护
      ②能够高效地实现组件之间的数据共享,提高开发效率
      ③存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步

    • 什么样的数据适合存储到Vuex中
      一般情况下,组件之间共享的数据,才有必要存储到 vuex 中
      对于组件中的私有数据,依旧存储在组件自身的 data 中即可

    1.3 Vuex的基本使用

    • 1、安装 Vuex 依赖包

    npm install vuex --save => 安装到运行时依赖 => 项目上线之后依然使用的依赖,开发时依赖 => 开发调试时使用

    开发时依赖 就是开开发的时候,需要的依赖,运行时依赖,项目上线运行时依然需要的

    • 2、导入 vuex 包
    // 创建 src/store/state.js
    export const state = {
        userName: null,
        token: null,
        title: '',
        roles: null
    }
    
    
    // 创建 src/store/index.js
    import {
        state
    } from './state'
    import Vuex from 'vuex'
    import Vue from 'vue'
    
    Vue.use(Vuex)
    
    
    • 3、在 src/store/index.js 创建 store 对象
    import { state } from './state'
    import Vuex from 'vuex'
    import Vue from 'vue'
    
    Vue.use(Vuex);
    export default new Vuex.Store({
      state: state,
      mutations: {
      },
      actions: {
      },
      getters: {
        showNum: state => {
          return '当前Count最新的数据为: '+ state.count 
        }
      },
      modules: {
      }
    })
    
    
    • 4、在 main.js 中将 store 对象挂载到 vue 实例中
    import store from './store/index';
    
    new Vue({
        router,
        store,
        el: '#app',
        render: h => h(App)
    }).$mount('#app');
    

    二、State 基本使用(共享数据存放)

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

    //  src/store/state.js
    export const state = {
        userName: null,
        token: null,
        title: '标题',
        roles: null,
        count: 0
    }
    

    2.1 组件访问 State 中数据的两种方式

    2.1.1 第一种:通过 this.$store.state.全局数据名称获取

    this.$store.state.全局数据名称(例如:this.$store.state.count,在模板中使用的话不需要 this)
    例如:

    <template>
        <div>
            <h3>当前最新的count值为:{{ $store.state.count}}</h3>
            <button>+1</button>
        </div>
    </template>
    <script>
    export default {
        data() {
            return {};
        }
    }
    </script>
    

    2.1.2 第二种通过 Vuex 中的 magState 函数按需导入当前组件需要的全局数据

    通过 Vuex 中的 magState 函数按需导入当前组件需要的全局数据,映射为当前组件的 computed 计算属性
    例如:

    <template>
        <div>
            <h3>当前最新的count值为:{{ count }} 的{{title}}</h3>
            <button>-1</button>
        </div>
    </template>
    <script>
    // 1、从Vuex中导入 mapState 函数
    import { mapState } from 'vuex'
    export default {
        data() {
            return {};
        },
        // 2、将全局数据,映射为当前组件的计算属性
        computed: {
            ...mapState(['count', 'title'])
        }
    }
    </script>
    

    三、mutations 的使用(共享数据操作:同步更新数据,函数中不可进行异步操作)

    为实现点击+1按钮,count自增+1,根据以往经验,很容易就会想到在组件的methods的处理函数中用 this.$store.state.count++ 来实现,这是不可取的,因为共享的数据,可能会在很多地方使用,如果每个组件都定义自己的处理方法,后期维护十分困难
    vue中推荐在store中mutations内的函数去操作共享数据

    mutations用户变更 Store 中的数据
    ①只能通过 mutations 变更 Store数据,不可以直接操作Store中的数据
    ②通过这种方式虽然操作稍微繁琐一些,但是可以集中监控所有数据的变化

    export default new Vuex.Store({
      state: state,
      mutations: {
        // 函数中第一个形参永远都是自身的 state,该形参就是上面的 state 对象
        add(state) {
          state.count++
        }
      },
      actions: {
      },
      modules: {
      }
    })
    

    3.1 触发 mutations 函数的两中方式

    3.1.1 第一种:this.$store.commit('函数名称'),commit的作用就是调用某个 mutations 函数

    <script>
    export default {
        data() {
            return {};
        },
        methods: {
            handle() {
                // 触发 mutations 的第一种方式,commit的作用就是调用某个 mutations 函数
                this.$store.commit('add')
            }
        }
    }
    </script>
    
    • vuex如果分为几个模块,方法是在模块中的话,如果直接在组件中通过this.$store.commit("方法名")是获取不到,必须要在前面加上模块名,如this.$store.commit("模块名/方法名")才可以获取到

    触发 mutations 时携带参数
    定义 mutations 函数时定义需要的参数

    // src/store/index.js
    export default new Vuex.Store({
      state: state,
      mutations: {
        add(state) {
          state.count++
        },
        addN(state, step) {
          state.count +=  step
        }
      },
      actions: {
      },
      modules: {
      }
    })
    
    // Addition.vue
    <template>
        <div>
            <h3>当前最新的count值为:{{ $store.state.count}}</h3>
            <button @click="handle">+4</button>
        </div>
    </template>
    <script>
    export default {
        data() {
            return {};
        },
        methods: {
            handle() {
                // 触发 mutations 函数时携带参数,第二个参数即为 mutations 函数的第二个形参
                this.$store.commit('addN', 4)
            }
        }
    }
    </script>
    
    

    3.1.2 第二种:通过 mapMutations 将需要的 mutations 函数导入并映射为当前组件的 methods 方法

    <template>
        <div>
            <h3>当前最新的count值为:{{ $store.state.count}}</h3>
            <button @click="handle">+1</button>
            <button @click="addN(4)">+N</button>
        </div>
    </template>
    <script>
    // 1、从 vuex 中导入 mapMutations 函数
    import { mapMutations } from 'vuex'
    export default {
        data() {
            return {};
        },
        methods: {
            handle() {
                this.$store.commit('add')
            },
            // 2、将指定的 mutations 函数映射为当前组件的 methods 函数
            ...mapMutations(['addN'])
    
        }
    }
    </script>
    
    

    四、actions 使用

    vuex中,mutations 函数不支持异步操作,如果在 mutations 函数中使用异步操作,会导致页面展示的数据与 state 中的数据不同步,导致出现问题

    actions 用于处理异步任务

    如果想通过异步操作变更数据,必须通过 actiongs ,而不能使用 mutations ,但是 actions 中还是需要通过触发 mutations 的的方式间接变更数据

    4.1 actions 的使用方式

    4.1.1 第一种方式: this.$store.dispatch('actions 函数')

    export default new Vuex.Store({
      state: state,
      mutations: {
        add(state) {
          state.count++
        },
        addN(state, step) {
          state.count = state.count + step
        }
      },
      actions: {
        // 第一个形参永远时 context, context 可以认为 New 出来的 Store对象
        addAsync(context) {
          setTimeout(() => {
            // 在 actions 中不能直接操作 state 中的数据
            context.commit('add')
          })
        }
      },
      modules: {
      }
    })
    
    // 组件中触发 Action
    <template>
        <div>
            <h3>当前最新的count值为:{{ $store.state.count}}</h3>
            <button @click="handle">+1</button>
            <button @click="addN(4)">+N</button>
            <button @click="addAsync1">+1 async</button>
        </div>
    </template>
    <script>
    import { mapMutations } from 'vuex'
    export default {
        data() {
            return {};
        },
        methods: {
            handle() {
                // 触发 mutations 的第一种方式
                this.$store.commit('add')
            },
            ...mapMutations(['addN']),
            addAsync1() {
                // 这里的 dispatch 函数专门用来触发 actions
                this.$store.dispatch('addAsync')
            }
    
        }
    }
    </script>
    
    

    注意:
    1、第一个形参永远时 context, context 可以认为 New 出来的 Store对象
    2、在 actions 中不能直接操作 state 中的数据,需要修改 state 中的数据,需要调用 mutations 中的函数

    4.1.2 触发 actions 异步任务时携带参数

    主要思路:在触发 actions 函数时携带参数,actions 函数使用形参接收到参数,在调用 mutations 函数传递过去

    //  src/store/index.js
    export default new Vuex.Store({
      state: state,
      mutations: {
        add(state) {
          state.count++
        },
        addN(state, step) {
          state.count = state.count + step
        }
      },
      actions: {
        // 第一个形参永远时 context, context 可以认为 New 出来的 Store对象
        addAsyncN(context, step) {
          setTimeout(() => {
            context.commit('addN', step)
          }, 1000)
        }
      },
      modules: {
      }
    })
    
    
    // 组件中
    <template>
        <div>
            <h3>当前最新的count值为:{{ $store.state.count}}</h3>
            <button @click="handle">+1</button>
            <button @click="addN(4)">+N</button>
            <button @click="addAsyncN">+N async</button>
        </div>
    </template>
    <script>
    import { mapMutations } from 'vuex'
    export default {
        data() {
            return {};
        },
        methods: {
            handle() {
                // 触发 mutations 的第一种方式
                this.$store.commit('add')
            },
            ...mapMutations(['addN']),
            addAsyncN() {
                // 这里的 dispatch 函数专门用来触发 actions 函数,并传递参数
                this.$store.dispatch('addAsyncN', 5)
            }
    
        }
    }
    </script>
    

    4.1.3 第二种方式: 通过 mapAction 将需要的 actions 函数导入并映射为当前组件的 methods 方法

    // src/store/index.js
    export default new Vuex.Store({
      state: state,
      mutations: {
        add(state) {
          state.count++
        },
        addN(state, step) {
          state.count += step
        },
        sub(state) {
          state.count--
        },
        subN(state, step) {
          state.count -= step
        }
      },
      actions: {
        // 第一个形参永远时 context, context 可以认为 New 出来的 Store对象
        addAsyncN(context, step) {
          setTimeout(() => {
            context.commit('addN', step)
          }, 1000)
        },
        subAsyncN(context, step){
          setTimeout(() => {
            context.commit('subN', step)
          }, 2000)
        }
      },
      modules: {
      }
    })
    
    
    // 组件
    <template>
        <div>
            <h3>当前最新的count值为:{{ count }} 的{{title}}</h3>
            <button @click="sub">-1</button>
            <button @click="subAsync">-2 AsyncN</button>
        </div>
    </template>
    <script>
    // 1、从vuex 中导入 mapActions 函数
    import { mapState, mapMutations, mapActions } from 'vuex'
    export default {
        data() {
            return {};
        },
        computed: {
            ...mapState(['count', 'title'])
        },
        methods: {
            ...mapMutations(['sub']),
            // 2、将指定的 actions 函数映射为当前组件的 methods 函数
            ...mapActions(['subAsyncN']),
            subAsync() {
                this.subAsyncN(2)
            }
        }
    }
    </script>
    

    五、Getter

    Getter 用于对 Store 中的数据进行加工处理形成新的数据。
    1、Getter 可以对 Store 中已有的数据加工之后形成新的数据,类似 vue 的计算属性
    2、Store 中数据发生变化,Getter的数据也会跟着变化
    3、Getter 不会修改 state 中的数据

    export default new Vuex.Store({
      state: state,
      mutations: {
        add(state) {
          state.count++
        },
        addN(state, step) {
          state.count += step
        },
        sub(state) {
          state.count--
        },
        subN(state, step) {
          state.count -= step
        }
      },
      actions: {
        subAsyncN(context, step){
          setTimeout(() => {
            context.commit('subN', step)
          }, 2000)
        }
      },
      modules: {
      },
      getters: {
        showNum: state => {
          return '当前Count最新的数据为: '+ state.count 
        }
      }
    })
    

    5.1 第一种访问 getters 中的数据:this.$store.getters.名称

    <template>
        <div>
            <h3>当前最新的count值为:{{ $store.state.count}}</h3>
            <button @click="handle">+1</button>
            <button @click="addN(4)">+N</button>
            <p>{{ $store.getters.showNum }}</p>
        </div>
    </template>
    <script>
    import { mapMutations } from 'vuex'
    export default {
        data() {
            return {};
        },
        methods: {
            handle() {
                // 触发 mutations 的第一种方式
                this.$store.commit('add')
            },
            ...mapMutations(['addN']),
        }
    }
    </script>
    

    5.2 第二种访问 getters 中的数据:mapGetters

    在 computed 属性中使用 mapGetters 导入需要的 getters 数据
    导入的数据就认为是组件的计算属性,可以直接在组件中使用

    <template>
        <div>
            <h3>当前最新的count值为:{{ count }} 的{{title}}</h3>
            <button @click="sub">-1</button>
            <button @click="subN(2)">-N</button>
            <p>{{ showNum }}</p>
        </div>
    </template>
    <script>
    // 1、从vuex 中导入 mapActions 函数
    import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
    export default {
        data() {
            return {};
        },
        computed: {
            ...mapState(['count', 'title']),
            ...mapGetters(['showNum'])
        },
        methods: {
            ...mapActions(['subAsyncN']),
            ...mapMutations(['sub', 'subN']),
        }
    }
    </script>
    
    

    六、模块化 Module

    6.1 为什么会有模块化

    由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
    这句话的意思是,如果把所有的状态都放在state中,当项目变得越来越大的时候,Vuex会变得越来越难以维护
    由此,又有了Vuex的模块化

    6.2 模块化的简单应用

    应用

    定义两个模块 usersetting

    user中管理用户的状态 token

    setting中管理 应用的名称 name

    const store  = new Vuex.Store({
      modules: {
        user: {
           state: {
             token: '12345'
           }
        },
        setting: {
          state: {
             name: 'Vuex实例'
          }
        }
      })
    

    定义child-b组件,分别显示用户的token和应用名称name

    <template>
      <div>
          <div>用户token {{ $store.state.user.token }}</div>
          <div>网站名称 {{ $store.state.setting.name }}</div>
      </div>
    </template>
    
    • 请注意: 此时要获取子模块的状态 需要通过 $store.state.模块名称.属性名 来获取

    看着获取有点麻烦,我们可以通过之前学过的getters(全局的getters)来改变一下

     getters: {
       token: state => state.user.token,
       name: state => state.setting.name
     } 
    
    • 请注意:这个getters是根级别的getters哦

    通过mapGetters引用

     computed: {
           ...mapGetters(['token', 'name'])
     }
    

    6.3 模块化中的命名空间

    命名空间 namespaced

    默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。
    这句话的意思是 刚才的user模块还是setting模块,它的 action、mutation 和 getter 其实并没有区分,都可以直接通过全局的方式调用 如

    如下:

      user: {
           state: {
             token: '12345'
           },
           mutations: {
            //  这里的state表示的是user的state
             updateToken (state) {
                state.token = 678910
             }
           }
        },
    

    通过mapMutations调用

     methods: {
           ...mapMutations(['updateToken'])
      }
     <button @click="updateToken">修改token</button>
    

    但是,如果我们想保证内部模块的高封闭性,我们可以采用namespaced来进行设置

    高封闭性?可以理解成 一家人如果分家了,此时,你的爸妈可以随意的进出分给你的小家,你觉得自己没什么隐私了,我们可以给自己的房门加一道锁(命名空间 namespaced),你的父母再也不能进出你的小家了

      user: {
           namespaced: true,
           state: {
             token: '12345'
           },
           mutations: {
            //  这里的state表示的是user的state
             updateToken (state) {
                state.token = 678910
             }
           }
        },
    

    使用带命名空间的模块 action/mutations

    方案1:直接调用-带上模块的属性名路径

    test () {
       this.$store.dispatch('user/updateToken') // 直接调用方法
    }
    

    方案2:辅助函数-带上模块的属性名路径

      methods: {
           ...mapMutations(['user/updateToken']),
           test () {
               this['user/updateToken']()
           }
       }
      <button @click="test">修改token</button>
    

    方案3: createNamespacedHelpers 创建基于某个命名空间辅助函数

    import { mapGetters, createNamespacedHelpers } from 'vuex'
    const { mapMutations } = createNamespacedHelpers('user')
    <button @click="updateToken">修改token2</button>
    
  • 相关阅读:
    CentOS 7 nginx+tomcat9 session处理方案之session保持
    利用tcp三次握手,使用awl伪装MAC地址进行多线程SYN洪水攻击
    Docker 基础 (一)
    去哪儿笔试的三个编程题
    [PAT乙级题解]——宇宙无敌加法器
    结构型设计模式
    行为型设计模式
    [PAT乙级题解]——快速排序
    创建型设计模式
    [PAT乙级题解]——试密码
  • 原文地址:https://www.cnblogs.com/DeryKong/p/15770757.html
Copyright © 2011-2022 走看看