最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • vuex

    正文概述 掘金(cabbage_li)   2021-02-02   531

    总结官方文档中的内容,方便自己看

    介绍

    专为vue.js开发的状态管理模式,把不同组件的共享状态抽取出来,以一个全局单例模式管理
    npm
    npm install vuex --save
    安装

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    

    store(仓库)
    基本就是一个容器,它包含着你的应用中大部分的状态(state)。
    vuex和单纯的全局对象有以下两点不同:
    1.Vuex的状态存储是响应式的。store中的状态改变,组件中也会更新。
    2.不能直接改变store中的状态。【应该提交mutation】
    创建Store

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          state.count++
        }
      }
    })
    

    使用 store.state 获取状态对象,通过 store.commit方法触发状态变更

    store.commit('increment')
    console.log(store.state.count) // -> 1
    

    为了在Vue组件中访问 this.$store property,需要为Vue实例提供创建好的store,需要在根组件注入store机制:

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

    然后可以从组件的方法提交一个变更:

    methods: {
      increment() {
        this.$store.commit('increment')
        console.log(this.$store.state.count)
      }
    }
    

    核心概念

    State


    单一状态树,用一个对象就包含了全部的应用层级状态,每当 ` store.state.count ` 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。

    mapState 辅助函数

    当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些复杂和冗余,这时可以使用mapState辅助函数帮助生成计算属性,可以帮助我们少按几次键

    import { mapState } from "vuex";
    computed: {
        // 使用对象展开运算符将此对象混入到外部对象中
        ...mapState(["count", "data01"]),
        }
    
    //使用
    console.log("count", this.count);
    

    Getters

    vueX允许我们在store中定义“getter”(可以认为是store中的计算属性)。有缓存,只有依赖值发生变化才会重新计算

    Getter 接受 state 作为其第一个参数:

    const store = new Vuex.Store({
      state: {
        todos: [
          { id: 1, text: '...', done: true },
          { id: 2, text: '...', done: false }
        ]
      },
      getters: {
        doneTodos: state => {
          return state.todos.filter(todo => todo.done)
        }
      }
    })
    

    通过属性访问
    Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:

    store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
    

    Getter 也可以接受其他 getter 作为第二个参数:

    getters: {
      // ...
      doneTodosCount: (state, getters) => {
        return getters.doneTodos.length
      }
    }
    

    通过方法访问
    可以通过让 getter 返回一个函数,来实现给 getter 传参。

    getters: {
      // ...
      getTodoById: (state) => (id) => {
        return state.todos.find(todo => todo.id === id)
      }
    }
    
    store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
    

    注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。

    mapGetters 辅助函数
    mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性

    import { mapGetters } from 'vuex'
    
    export default {
      // ...
      computed: {
      // 使用对象展开运算符将 getter 混入 computed 对象中
        ...mapGetters([
          "doneTodos",
          "doneTodosCount",
          // ...
        ])
      }
    }
    
     //使用时
     console.log("getter", this.doneTodos);
    

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

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

    Mutations

    更改Vuex的store中的状态的唯一方法是提交mutation。【提交mutation可以方便管理,直接修改state中的状态过于分散,不好管理】

    store中mutation进行修改状态

    const store = new Vuex.Store({
      state: {
        count: 1
      },
      mutations: {
        increment (state) {
          // 变更状态
          state.count++
        }
      }
    })
    

    组件中调用 store.coommit 方法:

    store.commit('increment')
    

    提交载荷(Payload)

    你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):

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

    在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:

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

    对象风格的提交方式

    提交 mutation 的另一种方式是直接使用包含 type 属性的对象:

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

    Mutation需遵守Vue的响应规则

    注意事项:

    1.最好提前在你的 store 中初始化好所有所需属性。
    2.当需要在对象上添加新属性时,应该
    *使用Vue.set(obj,'newProp',123)或者
    *以新对象替换老对象。例如,利用对象展开运算符:

      state.obj = {...state.obj,newProp:123}
    

    3.Mutation必须是同步函数

    在组件中提交 Mutation

    你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

    import { mapMutations } from 'vuex'
    
    export default {
      // ...
      methods: {
        ...mapMutations([
          'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
    
          // `mapMutations` 也支持载荷:
          'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
        ]),
        ...mapMutations({
          add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
        })
      }
    }
    

    Mutation都是同步事务 处理异步操作看Action

    Actions

    Action函数接受一个与store实例具有相同方法和属性的context对象,因此你可以调用context.commit提交一个mutation,或者通过context.state和context.getters来获取state和getters。
    Actions类似于mutation,不同在于:

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

    分发Action
    Action通过store.dispatch方法触发

    store.dispatch('increment')
    
    // 以载荷形式分发
    store.dispath('incrementAsync',{
       amount: 10
       })
    // 以对象形式分发
    store.dispatch({
      type: 'incrementAsync',
      amount: 10
    })
    
    //可以在action内部执行异步操作
    action: {
      incrementAsync ({ commit }) {
        setTimeout(() => {
          commit('increment')
        }, 1000)
      }
    }
    
    

    在组件中分发Action

    在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

    import { mapActions } from 'vuex'
    
    export default {
      // ...
      methods: {
        ...mapActions([
          'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
    
          // `mapActions` 也支持载荷:
          'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
        ]),
        ...mapActions({
          add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
        })
      }
    }
    

    组合Action

    Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?

    首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:

    actions: {
      actionA ({ commit }) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            commit('someMutation')
            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())
      }
    }
    

    一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。

    Module

    由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

    为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

    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 的状态
    

    项目结构

    vuex


    起源地下载网 » vuex

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元