关于Vuex 开发状态管理

225 阅读3分钟

Vuex简介

官方的解释: Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存 储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变 化。

快速理解:每个组件都有它自己数据属性,封装在data()中,每个组件之间data是完全隔离的,是私有的。如果我们需要各个组件都能访问到数据数据,或是需要各个组件之间能互相交换数据,这就需要一个单独存储的区域存放公共属性。这就是状态管理所要解决的问题。

工程搭建

# 创建一个基于 webpack 模板的新项目
vue init webpack vuexdemo
# 安装依赖,走你
cd vuexdemo
cnpm install ‐‐save vuex
npm run dev

读取状态值

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。

实现步骤: (1)在src下创建store,store下创建index.js

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

const store = new Vuex.Store({
  state: {
  count: 0
  }
})
export default store

(2)修改main.js,引入和装载store

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false
  new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>'
})

(3)修改components\HelloWorld.vue

<template>
  <div>
      {{$store.state.count}}
    <button @click="showCount">测试</button>
  </div>
 </template>

<script>
  export default {
  methods:{
    showCount(){
        console.log(this.$store.state.count)
    }
  }
}
</script>

3.改变状态值

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

(1)修改store/index.js ,增加mutation定义

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

(2)修改components\HelloWorld.vue ,调用mutation

<template>
  <div>
    {{$store.state.count}}
    <button @click="addCount">测试</button>
  </div>
</template>
<script>
  export default {
    methods:{
    addCount(){
      this.$store.commit('increment')
    }
  }
}
</script>

测试: 运行工程,点击测试按钮,我们会看到控制台和页面输出递增的数字

4.状态值共享测试

如果是另外一个页面,能否读取到刚才我在HelloWorld中操作的状态值呢?我们接下来就做一个测试.

(1)在components下创建show.vue

<template>
    <div>
    show: {{$store.state.count}}
    </div>
</template>

(2)修改路由设置 router/index.js

import Vue from 'vue'
import Router from 'vue‐router'
import HelloWorld from '@/components/HelloWorld'
import Show from '@/components/Show'
Vue.use(Router)
  export default new Router({
    routes: [
    {
        path: '/',
        name: 'HelloWorld',
        component: HelloWorld
    },
  {
    path: '/show',
    name: 'Show',
    component: Show
  }
  ]
})

测试: 在HelloWorld页面点击按钮使状态值增长,然后再进入show页面查看状态值

5.提交载荷

所谓载荷(payload)就是 向 store.commit 传入额外的参数。 (1)修改store下的index.js

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

(2)修改HelloWorld.vue

......
addCount(){
 this.$store.commit('increment',10)
 console.log(this.$store.state.count)
}
......

6.Action

Action 类似于 mutation,不同在于: Action 提交的是 mutation,而不是直接变更状态。 Action 可以包含任意异步操作。

我们现在使用 Action 来封装increment (1)修改store/index.js

const store = new Vuex.Store({
  .....
    actions: {
    increment (context){
    context.commit('increment',10)
    }
  }
})

(2)修改show.vue

<template>
    <div>
      show: {{$store.state.count}}
      <button @click="addCount">测试</button>
    </div>
</template>
<script>
  export default {
    methods:{
      addCount(){
          this.$store.dispatch('increment')
          console.log(this.$store.state.count)
      }
  }
}
</script>

我们使用dispatch来调用action , Action也同样支持载荷.

7 派生属性Getter

有时候我们需要从 store 中的 state 中派生出一些状态,例如我们在上例代码的基础上,我们增加一个叫 remark的属性,如果count属性值小于50则remark为加油,大于等于50小于100则remark为你真棒,大于100则remark的值为你是大神. 这时我们就需要用到getter为我们解决。

(1)修改store/index.js ,增加getters定义

const store = new Vuex.Store({
    ......
    getters: {
        remark(state){
        if(state.count<50){
            return '加油'
        }else if( state.count<100){
            return '你真棒'
        }else{
            return '你是大神'
        }
    }
}
.......
})

Getter 接受 state 作为其第一个参数,也可以接受其他 getter 作为第二个参数 (2)修改HelloWorld.vue 显示派生属性的值

{{$store.getters.remark}}

模块化

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,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 的状态