zoukankan      html  css  js  c++  java
  • vue(23)Vuex的5个核心概念

    Vuex的核心概念

    Vuex有5个核心概念,分别是StateGettersmutationsActionsModules
     

    State

      Vuex使用单一状态树,也就是说,用一个对象包含了所有应用层级的状态,作为唯一数据源而存在。没一个Vuex应用的核心就是storestore可理解为保存应用程序状态的容器。store与普通的全局对象的区别有以下两点:
      (1)Vuex的状态存储是响应式的。当Vue组件从store中检索状态的时候,如果store中的状态发生变化,那么组件也会相应地得到高效更新。
      (2)不能直接改变store中的状态。改变store中的状态的唯一途径就是显式地提交mutation。这可以确保每个状态更改都留下可跟踪的记录,从而能够启用一些工具来帮助我们更好的理解应用
      安装好Vuex之后,就可以开始创建一个store,代码如下:

    const store =  new Vuex.Store({
      // 状态数据放到state选项中
      state: {
        counter: 1000,
      },
      // mutations选项中定义修改状态的方法
      // 这些方法接收state作为第1个参数
      mutations: {
        increment(state) {
          state.counter++;
        },
      },
    });
    

      在组件中访问store的数据,可以直接使用store.state.count。在模块化构建系统中,为了方便在各个单文件组件中访问到store,应该在Vue根实例中使用store选项注册store实例,该store实例会被注入根组件下的所偶遇子组件中,在子组件中就可以通过this.$store来访问store。代码如下:

    new Vue({
      el: "#app",
      store,
    })
    

      如果在组件中要展示store中的状态,应该使用计算属性来返回store的状态,代码如下:

    computed: {
        count(){
            return this.$store.state.count
        }
    }
    

      之后在组件的模板中就可以直接使用count。当storecount发生改变时,组件内的计算属性count也会同步发生改变。
      那么如何更改store中的状态呢?注意不要直接去修改count的值,例如:

    methods: {
        handleClick(){
            this.&store.state.count++;    // 不要这么做
        }
    }
    

      既然选择了Vuex作为你的应用的状态管理方案,那么就应该遵照Vuex的要求;通过提交mutation来更改store中的状态。在严格模式下,如果store中的状态改变不是有mutation函数引起的,则会抛出错误,而且如果直接修改store中的状态,Vue的调试工具也无法跟踪状态的改变。在开发阶段,可以开启严格模式,以避免字节的状态修改,在创建store的时候,传入strict: true代码如下:

    const store = new Vuex.Store({
        strict: true
    })
    

      Vuex中的mutation非常类似于事件:每个mutation都有一个字符串的事件类型和一个处理器函数,这个处理器函数就是实际进行状态更改的地方,它接收state作为第1个参数。
      我们不能直接调用一个mutation处理器函数,mutations选项更像是事件注册,当触发一个类型为incrementmutation时,调用此函数。要调用一个mutation处理器函数,需要它的类型去调用store.commit方法,代码如下:

    store.commit("increment")
    

    Getters

      假如在store的状态中定义了一个图书数组,代码如下:

    export default new Vuex.Store({
      state: {
        books: [
          { id: 1, title: "Vue.js", isSold: false },
          { id: 2, title: "common.js", isSold: true },
          { id: 3, title: "node.js", isSold: true },
        ],
      },
    })
    

      在组件内需要得到正在销售的书,于是定义一个计算属性sellingBooks,对state中的books进行过滤,代码如下:

    computed: {
        sellingBooks(){
            return this.$store.state.books.filter(book => book.isSold === true);
        }
    }
    

      这没有什么问题,但如果是多个组件都需要用到sellingBooks属性,那么应该怎么办呢?是复制代码,还是抽取为共享函数在多处导入?显然,这都不理想
      Vuex允许我们在store中定义getters(可以认为是store的计算属性)。与计算属性一样,getter的返回值会根据它的依赖项被缓存起来,且只有在它的依赖项发生改变时才会重新计算。
      getter接收state作为其第1个参数,代码如下:

    export default new Vuex.Store({
      state: {
        books: [
          { id: 1, title: "Vue.js", isSold: false },
          { id: 2, title: "common.js", isSold: true },
          { id: 3, title: "node.js", isSold: true },
        ],
      },
      getters: {
        sellingBooks(state) {
          return state.books.filter((b) => b.isSold === true);
        },
      }
    })
    

      我们定义的getter将作为store.getters对象的竖向来访问,代码如下;

    <h3>{{ $store.getters.sellingBooks }}</h3>
    

    getter也可以接收其他getter作为第2个参数,代码如下:

    getters: {
        sellingBooks(state) {
          return state.books.filter((b) => b.isSold === true);
        },
        sellingBooksCount(state, getters) {
          return getters.sellingBooks.length;
        },
    }
    

      在组件内,要简化getter的调用,同样可以使用计算属性,代码如下:

    computed: {
        sellingBooks() {
          return this.$store.getters.sellingBooks;
        },
        sellingBooksCount() {
          return this.$store.getters.sellingBooksCount;
        },
      },
    

      要注意,作为属性访问的getter作为Vue的响应式系统的一部分被缓存。
      如果想简化上述getter在计算属性中的访问形式,可以使用mapGetters辅助函数。mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:

    import { mapGetters } from 'vuex'
    
    export default {
      // ...
      computed: {
      // 使用对象展开运算符将 getter 混入 computed 对象中
        ...mapGetters([
            "sellingBooks", 
            "sellingBooksCount"
        ]),
      }
    }
    

    如果你想将一个 getter 属性另取一个名字,使用对象形式:

    ...mapGetters({
      // 把 `this.booksCount` 映射为 `this.$store.getters.sellingBooksCount`
      booksCount: 'sellingBooksCount'
    })
    

      getter还有更灵活的用法,用过让getter返回一个函数,来实现给getter传参。例如,下面的getter根据图书ID来查找图书对象

    getters: {
        getBookById(state) {
          return function (id) {
            return state.books.filter((book) => book.id === id);
          };
        },
    }
    

      如果你对箭头函数已经掌握的炉火纯青,那么可以使用箭头函数来简化上述代码

    getters: {
        getBookById(state) {
          return (id) => state.books.filter((book) => book.id === id);
        },
    

    下面在组件模板中的调用返回{ "id": 1, "title": "Vue.js", "isSold": false }

    <h3>{{ $store.getters.getBookById(1) }}</h3>
    

    mutation

    上面已经介绍了更改store中的状态的唯一方式是提交mutation
     

    提交载荷(Payload)

    在使用store.commit方法提交mutation时,还可以传入额外的参数,即mutation的载荷(payload),代码如下:

    mutations: {
        increment(state, n) {
          state.counter+= n;
        },
      },
    
    store,commit("increment", 10)
    

    载荷也可以是一个对象,代码如下:

    mutations: {
      increment (state, payload) {
        state.count += payload.amount
      }
    }
    
    store.commit('increment', {
      amount: 10
    })
    

    对象风格的提交方式

    提交mutation时,也可以使用包含type属性的对象,这样传一个参数就可以了。代码如下所示:

    store.commit({
      type: "increment",
      amount: 10
    })
    

    当使用对象风格提交时,整个对象将作为载荷还给mutation函数,因此处理器保持不变。代码如下:

    mutations: {
      increment (state, payload) {
        state.count += payload.amount
      }
    }
    

    在组件中提交mutation时,使用的是this.$store.commit("increment"),如果你觉得这样比较繁琐,可以使用mapMutations辅助函数将组件中的方法映射为store.commit调用,代码如下:

    import { mapMutations } from "vuex";
    methods: {
        ...mapMutations([
          // 将this.increment()映射为this.$store.commit("increment")
          "increment",
        ]),
    }
    

    除了使用字符串数组外,mapMutations函数的参数也可以是一个对象

    import { mapMutations } from "vuex";
    methods: {
        ...mapMutations([
          // 将this.add()映射为this.$store.commit("increment")
          add: "increment",
        ]),
    }
    

    Mutation 需遵守 Vue 的响应规则

    既然 Vuexstore 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:

    1.最好提前在你的 store 中初始化好所有所需属性。
    2.当需要在对象上添加新属性时,你应该

    • 使用 Vue.set(obj, 'newProp', 123), 或者
    • 以新对象替换老对象。例如,利用对象展开运算符 (opens new window)我们可以这样写:
    state.obj = { ...state.obj, newProp: 123 }
    

    使用常量替代 Mutation 事件类型

    我们可以使用常量来替代mutation类型。可以把常量放到一个单独的JS文件中,有助于项目团队对store中所包含的mutation一目了然,例如:

    // mutation-types.js
    export const INCREMENT = "increment";
    
    // store.js
    import Vuex from "vuex";
    import { INCREMENT } from "./mutation-types";
    const store = new Vuex.Store({
      state: { ... },
      mutations: {
        // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
        [INCREMENT] (state) {
          // mutate 状态
        }
      }
    })
    

    Actions

      在定义mutation时,有一个重要的原则就是mutation必须是同步函数,换句话说,在mutation处理器函数中,不能存在异步调用,比如

    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          setTimeout( () => {
            state.count++
          }, 2000)
        }
      }
    })
    

      在increment函数中调用setTimeout()方法在2s后更新count,这就是一个异步调用。记住,不要这么做,因为这会让调试变得困难。假设正在调试应用程序并查看devtool中的mutation日志,对于每个记录的mutationdevtool都需要捕捉到前一状态的快照。然而,在上面的例子中,mutation中的setTimeout方法中的回调让这不可能完成。因为当mutation被提交的时候,回调函数还没有被调用,devtool也无法知道回调函数什么时候真正被调用。实际上,任何在回调函数中执行的状态的改变都是不可追踪的。
      如果确实需要执行异步操作,那么应该使用actionaction类似于mutation,不同之处在于:

    • action提交的是mutation,而不是直接变更状态。
    • action可以包含任意异步操作

    一个简单的action示例如下:

    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
            state.count++
        }
      },
      actions: {
        increment(context) {
          context.commit("increment");
        },
      },
    })
    

      Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.statecontext.getters 来获取 stategetters。甚至可以用context.dispatch调用其他的action。要注意的是,context对象并不是store实例本身
      如果在action中需要多次调用commit,则可以考虑使用ECMAScript6中的解构语法来简化代码,如下所示:

    actions: {
        increment({ commit }) {
          commit("increment");
        },
      },
    

      action通过store.dispatch方法触发,代码如下:

    actions: {
        incrementAsync({ commit }) {
          setTimeout(() => {
            commit("increment");
          }, 2000);
        },
      },
    

      action同样支持载荷和对象方式进行分发。代码如下所示:

    // 载荷是一个简单的值
    store.dispatch("incrementAsync", 10)
    
    // 载荷是一个对象
    store.dispatch("incrementAsync", {
      amount: 10
    })
    
    // 直接传递一个对象进行分发
    store.dispatch({
      type: "incrementAsync",
      amount: 10
    })
    

      在组件中可以使用this.$store.dispatch("xxx")分发action,或者使用mapActions辅助函数将组件的方法映射为store.dispatch调用,代码如下:

    // store.js
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          state.count++
        },
        incrementBy(state, n){
          state.count += n;
        }
      },
      actions: {
        increment({ commit }) {
          commit("increment");
        },
        incrementBy({ commit }, n) {
          commit("incrementBy", n);
        },
      },
    })
    
    
    // 组件
    <template>
      <div id="app">
        <button @click="incrementNumber(10)">+10</button>
      </div>
    </template>
    
    import { mapActions } from "vuex";
    export default {
      name: "App",
      methods: {
        ...mapActions(["increment", "incrementBy"]),
    };
    

      action通常是异步的,那么如何知道action何时完成呢?更重要的是,我们如何才能组合多个action来处理更复杂的异步流程呢?
      首先,要知道是store.dispatch可以处理被触发的action的处理函数返回的Promise,并且store.dispatch仍旧返回Promise,例如:

    actionA({ commit }) {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              commit("increment");
              resolve();
            }, 1000);
          });
        },
    

    现在可以:

    store.dispatch("actionA").then(() => {
    ...
    })
    

    在另外一个action中也可以

    actions: {
      //...
      actionB({dispatch, commit}) {
        return dispatch("actionA").then(() => {
          commit("someOtherMutation")
        })
      }
    }
    

    最后,如果我们利用 async / await (opens new window),我们可以如下组合 action

    // 假设 getData() 和 getOtherData() 返回的是 Promise
    
    actions: {
      async actionA ({ commit }) {
        commit('gotData', await getData())
      },
      async actionB ({ dispatch, commit }) {
        await dispatch('actionA') // 等待 actionA 完成
        commit('gotOtherData', await getOtherData())
      }
    }
    

    Module

      由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
      为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 statemutationactiongetter、甚至是嵌套子模块——从上至下进行同样方式的分割:

    const moduleA = {
      state: () => ({ ... }),
      mutations: { ... },
      actions: { ... },
      getters: { ... }
    }
    
    const moduleB = {
      state: () => ({ ... }),
      mutations: { ... },
      actions: { ... }
    }
    
    const store = new Vuex.Store({
      modules: {
        a: moduleA,
        b: moduleB
      }
    })
    
    store.state.a // -> moduleA 的状态
    store.state.b // -> moduleB 的状态
    

    模块的局部状态

    对于模块内部的 mutationgetter,接收的第一个参数是模块的局部状态对象。

    const moduleA = {
      state: () => ({
        count: 0
      }),
      mutations: {
        increment (state) {
          // 这里的 `state` 对象是模块的局部状态
          state.count++
        }
      },
    
      getters: {
        doubleCount (state) {
          return state.count * 2
        }
      }
    }
    

    同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState

    const moduleA = {
      // ...
      actions: {
        incrementIfOddOnRootSum ({ state, commit, rootState }) {
          if ((state.count + rootState.count) % 2 === 1) {
            commit('increment')
          }
        }
      }
    }
    

    对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:

    const moduleA = {
      // ...
      getters: {
        sumWithRootCount (state, getters, rootState) {
          return state.count + rootState.count
        }
      }
    }
    

    项目结构

    Vuex 并不限制你的代码结构。但是,它规定了一些需要遵守的规则:
    1.应用层级的状态应该集中到单个 store 对象中。
    2.提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。
    3.异步逻辑都应该封装到 action 里面。

    只要你遵守以上规则,如何组织代码随你便。如果你的 store 文件太大,只需将 actionmutationgetter 分割到单独的文件。

    对于大型应用,我们会希望把 Vuex 相关代码分割到模块中。下面是项目结构示例:

    └── store
        ├── index.js          # 我们组装模块并导出 store 的地方
        ├── actions.js        # 根级别的 action
        ├── mutations.js      # 根级别的 mutation
        └── modules
            ├── cart.js       # 购物车模块
            └── products.js   # 产品模块
    
  • 相关阅读:
    MYSQL 写入emoji表情字符处理
    openfire4.0.2源码 使用 IntelliJ IDEA 搭建开发环境
    strophe.js 插件 XMPP openfire
    OPENFIRE 使用Hazelcast插件进行集群
    LINUX提高openfire并发数(网上收集)
    LINUX 安装JDK (rpm格式和tar.gz格式)
    OPENFIRE 接收数据流程图
    OPENFIRE 启动流程
    linux查看cuda版本
    NvvmSupportError: libNVVM cannot be found. Do conda install cudatoolkit: library nvvm not found
  • 原文地址:https://www.cnblogs.com/jiakecong/p/15058200.html
Copyright © 2011-2022 走看看