您的当前位置:首页正文

vuex状态管理模式

来源:图艺博知识网

对于学习过react的同学可能比较清楚,在react我们是通过redux来处理状态管理的,那么现在火热的vue是如何做到管理页面数据的呢,答案就是vuex。

1 什么情况下使用vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。如果您需要构建是一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。

下面展示一个单向数据流的图片:


页面中模版获取state数据渲染页面,用户通过action改变数据导致页面重新渲染。

2 vuex Store

每一个 Vuex 应用的核心就是 store(仓库)。"store" 基本上就是一个容器,它包含着你的应用中大部分的状态(state)。Vuex 和单纯的全局对象有以下两点不同:

Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交(commit) mutations。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

const store = new Vuex.Store({
  state: {
    count: 0,
    step:2
  },
  mutations: {
    increment (state) {
      state.count += state.step
    }
  }
})

console.log(store.state.count) // -> 2

3vuex State

// 创建一个 Counter 组件
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return store.state.count
    }
  }
}

计算属性示例:

<div id="example">
  <p>my score grade: "{{ level }}"</p>
  <p>i get  "{{ score }}" point in exam</p>
  <button @click="change()">add</button>
</div>
var vm = new Vue({
  el: '#example',
  data: {
    score: '87'
  },
  computed: {
    level: function () {
      return this.score > 60 ?  '合格' :'不合格'
    }
  },
  method:{
     change:function(){
        this.score += 5
}
}
})

我们可以看到level是依赖于score的,如果我们通过点击button方法,会同是重新计算level的值。

Vuex 通过 store 选项,提供了一种机制将状态从根组件『注入』到每一个子组件中(需调用 Vue.use(Vuex)):

const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

4 mapState 辅助函数

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

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
const store = new Vuex.store({
     state:{
        apple:5,
        orange:2
}
})

export default {
    computed: mapState({
    // 箭头函数可使代码更简练
    apple: state => state.apple,
    total (state) {
      return state.apple + state.orange
    }
  })
}

上面这个例子显然易见,我们把store中的数据放到了页面上。
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
computed: mapState([
// 映射 this.count 为 store.state.count
'apple,orange'
])

有了对象扩展符,我们可以这样写:

computed: {
     attribute1:function(){
    },
     ...mapState([apple,orange])
}

5 vuex Getter

Vuex 允许我们在 store 中定义『getters』(可以认为是 store 的计算属性)。Getters 接受 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)
    }
  }
})

Getters 会暴露为 store.getters 对象:

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

Getters 也可以接受其他 getters 作为第二个参数:

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

我们可以很容易地在任何组件中使用它:

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

getters的神奇之处就是参数可以有2个,state和getters,所以这就有无限可能。

6 mapGetters 辅助函数

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

import { mapGetters } from 'vuex'
const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false },
      { id: 3, text: '...', done: true },
   ],
   another:2
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    },
   doneCount:(state,getter){
      return state.another + getters.doneCounts.length
    }
  }
})

export default {
  computed: {
    ...mapGetters([
      'doneTodosCount',
      'doneCount',
      // ...
    ])
  }
}

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

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

7 Mutation

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutations 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

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

 10)

其实我还可以传对象。

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

对象风格的提交方式


  type: 'increment',
  amount: 10
})

当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数,因此 handler 保持不变

接下来知道我要讲什么嘛,没错就是map了。。。

import { mapMutations } from 'vuex'

computed: {
    ...mapGetters([
      'doneTodosCount',
      'count',
    ])
},
methods: {
     ...mapMutations([
        'increment','decrement',
    ]),
     change(){
         this.increment()   == 
         this.doneTodosCount += this.count       
   }

注意执行了increment后count的值发生了变化。

8 vuex Action

Action 类似于 mutation,不同在于:

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

让我们来注册一个简单的 action:

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

乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

通过store.dispatch('increment')分发。举个例子说吧


import * as types from './mutation-types'

const store = new vex.store({
  mutation:{
     addcart(state, product){
         state.count += product.num
   }
 },
  actions: {
  addToCart ({ commit, state }, product) => {
  if (product.inventory > 0) {
    commit(types.ADD_TO_CART, {
       num: product.num
    })
  }
}

可以用store.dispatch('addToCart',{num:3,name:'fruit'})来分发。
当然这个也有map用法,和前面讲的一样。

组合 Actions

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

store.dispatch('actionA').then(() => {
  // ...
})

对promise不够了解的可以去学一下。

在另外一个 action 中也可以:

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

好了,今天讲的东西有点多,下回我会结合实际项目详解vuex的用法。

Top