君陌离的博客

vuePress-theme-reco 君陌离    2018 - 2020
君陌离的博客 君陌离的博客

Choose mode

  • dark
  • auto
  • light
首页
我的作品
  • 项目橱窗
  • blog模板
分类
  • 数据库
  • CSS
  • 摘记
  • JS
  • Node
  • Vue
  • React
  • GIT
  • Promise
  • Liunx
  • Xshell
  • ajax
  • WINDOWS
  • Python
  • 随笔
  • 脚手架
  • node
  • 自动化
标签
笔记
时间线
About Me
  • 关于我
  • 赞赏
Contact
  • GitHub
  • QQ
author-avatar

君陌离

70

文章

90

标签

首页
我的作品
  • 项目橱窗
  • blog模板
分类
  • 数据库
  • CSS
  • 摘记
  • JS
  • Node
  • Vue
  • React
  • GIT
  • Promise
  • Liunx
  • Xshell
  • ajax
  • WINDOWS
  • Python
  • 随笔
  • 脚手架
  • node
  • 自动化
标签
笔记
时间线
About Me
  • 关于我
  • 赞赏
Contact
  • GitHub
  • QQ
  • HTML5

  • JS

  • 微信小程序

  • 数据库

  • React

  • Vue

    • Vue知识点
    • Vuex中的核心内容
    • Vue三种传参方式
    • Vue的钩子函数[路由导航守卫、keep-alive]
    • Vue自定义指令,插槽,监听
    • Vue生命周期
  • vuepress

Vuex中的核心内容

vuePress-theme-reco 君陌离    2018 - 2020

Vuex中的核心内容

君陌离 2020-08-07 14:44:26 Vuex

# Vuex中的核心内容

  • state:包含了store中存储的各个状态。
  • getter: 类似于 Vue 中的计算属性,根据其他 getter 或 state 计算返回值。
  • mutation: 一组方法,是改变store中状态的执行者,只能是同步操作。
  • action: 一组方法,其中可以包含异步操作。
  • modules: 模块化状态管理

# State

  • Vuex 使用 state 来存储应用中需要共享的状态。为了能让 Vue 组件在 state更改后也随着更改,需要基于state 创建计算属性。
// 创建一个 Counter 组件
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count  // count 为某个状态
    }
  }
}
1
2
3
4
5
6
7
8
9

# Getter

  • 类似于 Vue 中的 计算属性(可以认为是 store 的计算属性),getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

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)
    }
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
  • Getter 会暴露为 store.getters 对象,可以以属性的形式访问这些值:
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
1
  • Getter 方法也接受 state和其他getters作为前两个参数。
getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}
1
2
3
4
5
6
store.getters.doneTodosCount // -> 1
1

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

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}
1
2
3
4
5

也可以通过让 getter 返回一个函数,来实现给 getter 传参。在对 store 里的数组进行查询时非常有用。

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

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

# Mutation

  • 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。也就是说,前面两个都是状态值本身,mutations才是改变状态的执行者。

注意:mutations只能是同步地更改状态。

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})
1
2
3
4
5
6
7
8
9
10
11

调用 store.commit 方法:

store.commit('increment')
1

传参

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}
1
2
3
4
5
6

页面中调用

this.$store.commit('increment', 10)
1

# Action

  • 想要异步地更改状态,就需要使用action。action并不直接改变state,而是发起mutation。

注册一个简单的 action:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

在action内部执行异步操作:

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}
1
2
3
4
5
6
7

发起action的方法形式和发起mutation一样,只是换了个名字dispatch。

// 以对象形式分发Action
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})
1
2
3
4
5

# Action与Mutation的区别

  • Action 类似于 mutation,不同在于:

    Action 提交的是 mutation,而不是直接变更状态。 Action 可以包含任意异步操作,而Mutation只能且必须是同步操作。

# Module

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

代码示例:

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 的状态
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  • 嵌套子模块

首先创建子模块的文件:

// products.js

// initial state
const state = {
  added: [],
  checkoutStatus: null
}
// getters
const getters = {
  checkoutStatus: state => state.checkoutStatus
}
// actions
const actions = {
  checkout ({ commit, state }, products) {
  }
}
// mutations
const mutations = {
  mutation1 (state, { id }) {
  }
}
export default {
  state,
  getters,
  actions,
  mutations
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

然后在总模块中引入:

import Vuex from 'vuex'
import products from './modules/products' //引入子模块
Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    products   // 添加进模块中
  }
})
1
2
3
4
5
6
7
8
9

# 各个模块与 Vue 组件结合

将state和getter结合进组件需要使用计算属性:

computed: {
  count () {
    return this.$store.state.count
    // 或者 return this.$store.getter.count
  }
}
1
2
3
4
5
6

将mutation和action结合进组件需要在methods中调用this.$store.commit()或者this.$store.commit():

methods: {
    changeDate () {
        this.$store.commit('change');
    },
    changeDateAsync () {
        this.$store.commit('changeAsync');
    }
}
1
2
3
4
5
6
7
8

为了简便起见,Vuex 提供了四个辅助函数方法用来方便的将这些功能结合进组件。
mapState
mapGetters
mapMutations
mapActions
示例代码:

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

export default {
    // ...
    computed: {
      localComputed () { /* ... */ },
        // 使用对象展开运算符将此对象混入外部对象中
      ...mapState({
        // 为了能够使用 `this` 获取局部状态,必须使用常规函数
        count(state) {
          return state.count + this.localCount
        }
      }),
      ...mapGetters({
        getterCount(state, getters) {
          return state.count + this.localCount
        }
      })
    }
    methods: {
      ...mapMutations({
          // 如果想将一个属性另取一个名字,使用以下形式。注意这是写在对象中
           add: 'increment' // 将 `this.add()` 映射为`this.$store.commit('increment')`
        }),
      ...mapActions({
          add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
        })
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

如果结合进组件之后不想改变名字,可以直接使用数组的方式。

methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
}
1
2
3
4
5
6
7
8
欢迎来到 您的站点名称($site.title)
看板娘