Vuex

243 阅读2分钟

一、 Vuex 是什么?

  • Vuex 是一个专门为 vue.js 应用程序开发的状态(状态就是数据)管理模式,它采用集中式存储管理应用的状态。相当于把组件中的数据提升到一个全局的地方,这个地方就是Vuex 的 store(仓库),由 Vuex 统一管理,如果某个组件需要这个数据,直接从store中获取。

  • 如果要修改存在vuex中的数据,需要在定义store时,定义修改这个数据的方法,这些方法称为mutation;

  • mutation函数的第一个参数是state对象,所有的数据都定义state中,在mutation函数中通过state可以修改 上面state中的数据;

  • 注意mutation中修改数据只能使用同步的方式,不能再异步的操作中更新数据;如果有异步就需要使用action;

  • action 也是更新数据的方式,action不同于mutation的是 action 可以使用异步,但是更新数据仍然需要 commit 对应的mutation;

二、使用 vuex 的步骤

  • 在此之前,你需要安装 vuex,如果是 vue-cli ,在初始化项目时选择 vuex

1.把需要放到 Vuex 中的数据存在 state里面

2.创建修改这些数据的mutation

3.如果这些数据需要异步更新,则创建对应的 action , 并且在 action 中通过 commit mutation 的方式更新数据

4.最后导出 Vuex 的 stroe 实例,并且为Vue的根实例配置 store属性,配置 store属性后,在Vue实例中可以通过 this.$store 访问store

5.在整个Vue的应用中,任何地方需要使用该数据,通过 this.$store.state.属性名 的方式获取数据;

6.如果需要更新这些数据可以通过调用this.store.commit(mutation函数名),如果是异步更新,需要 this.store.dispatch(action名)

三、 示例

  • store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // state就是数据,如果数据定义在state中组件中如果要使用这个数据 this.$store.state.属性名 的方式获取
    num: 15
  },
  mutations: {
    // state 中的数据不能被直接修改,如果要修改这些数据,需要使用mutation,注意mutation中不能使用异步更新state
    add (state) {
      // mutation函数的第一个参数是state对象,所有的数据都定义state中,在mutation函数中通过state可以修改 上面state中的数据;
      state.num++
    },
    addNum (state, payload) {
      // mutation的第二个参数 payload是在 commit mutation时传入的参数
      state.num += payload
    }
  },
  actions: {
    // action可以使用异步,但是更新数据仍然需要 commit 对应的mutation
    asyncAdd(context) {
      setTimeout(() => {
        context.commit('add')
      }, 1000)
    }
  }
})

  • App.vue
<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
      <h1>someNum: {{$store.state.num}}</h1>
    </div>
    <router-view/>
  </div>
</template>

<script>
import Bus from './bus'
export default {
  name: 'App',
  data () {
    return {}
  }
}
</script>

  • Home.vue
<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <div>
      <button @click="add">给上面的sumNum加加</button>
      <button @click="add2">给上面的sumNum加2</button>
    </div>
  </div>
</template>

<script>

export default {
  name: 'home',
  methods: {
    add () {
      this.$store.commit('addOne') // commit mutation
      this.$store.dispatch('asyncAdd') // dispatch action
    },
    add2 () {
      this.$store.commit('addNum', 2) // 传递payload
    }
  }
}
</script>


四、mapState/mapMutations/mapActions

如果使用很多个 store 中的数据和方法时通过 this.$store 的方式很不方便,vuex 提供了三个对应的方法用于批量获取多个 state、mutation、action;

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
// import Bus from '../bus'

import { mapState, mapMutations, mapActions } from 'vuex'

export default {
  name: 'home',
  methods: {
    updateX (e) {
      this.$store.commit('changeX', e.target.value)
    },
    updateSex(e) {
      this.$store.commit('changeSex', e.target.value)
    },
    add () {
       this.addOne() // 等效于 this.$store.commit('addOne')
    },
    add2 () {
       this.addNum(2); // 等效于 this.$store.commit('addNum', 2)
    },
    add3 () {
       this.asyncAdd2(); // 等效于 this.$store.dispatch('asyncAdd')
    },
    ...mapMutations(['addOne', 'addNum']),
    ...mapActions({
      asyncAdd2: 'asyncAdd' // 重命名
    })

  },
  computed: {
    ...mapState(['num'])
  },
  components: {
    HelloWorld
  }
}
</script>

  • 通过 mapState、mapMutations、mapActions 方法结合展开运算符,可以把对应的数据和方法添加到computed和methods中的,这些数据方法都可以通过 this 实例访问