Vuex的基本使用与概念解析

一、什么情况下应该使用 Vuex?

Vuex 可以帮助我们管理共享状态,并附带了更多的概念和框架。这需要对短期和长期效益进行权衡。
如果不打算开发大型单页应用,应用够简单,最好不要使用 Vuex。一个简单的 store 模式就足够了。但是,如果需要构建一个中大型单页应用,就要考虑如何更好地在组件外部管理状态,Vuex 是不错的选择。

二、基本使用

在 Vue 的单页面应用中使用,需要使用Vue.use(Vuex)调用插件。将其注入到Vue根实例中。

import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0
  },
  getter: {
    
    
    doneTodos: (state, getters) => {
    
    
      return state.todos.filter(todo => todo.done)
    }
  },
  mutations: {
    
    
    increment (state, payload) {
    
    
      state.count++
    }
  },
  actions: {
    
    
    addCount(context) {
    
    
      // 可以包含异步操作
      // context 是一个与 store 实例具有相同方法和属性的 context 对象
    }
  }
})
// 注入到根实例
new Vue({
    
    
  render: h => h(App),
  store
}).$mount('#app')

然后改变状态:

this.$store.commit('increment')

三、核心

Vuex 主要有四部分:

1.state:包含了store中存储的各个状态。
2.getter:类似于 Vue 中的计算属性,根据其他 getter 或 state 计算返回值。
3.mutation:一组方法,是改变store中状态的执行者,只能是同步操作。
4.action:一组方法,其中可以包含异步操作。
在这里插入图片描述

1、State:

Vuex 使用 state 来存储应用中需要共享的状态。为了能让 Vue 组件在 state更改后也随着更改,需要基于state 创建计算属性。

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

注意:一般不通过state来直接修改属性,而是通过mutations来修改。

2、Getters

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

Getters中的方法有两个默认参数:
state 当前VueX对象中的状态对象
getters 当前getters对象,用于将getters下的其他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)
    }
  }
})

通过属性访问:

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

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

Getter 方法也接受 state和当前getters对象作为前两个参数:

getters: {
    
    
  doneTodos: state => {
    
    
      return state.todos.filter(todo => todo.done)
    }
  doneTodosCount: (state, getters) => {
    
    
    return getters.doneTodos.length //调用当前getter下的其他getter函数
  }
}
store.getters.doneTodosCount // -> 1

在任何组件中使用它:

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

注意: getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的。

通过方法访问:

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

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

3、Mutation

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

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

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

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

调用 store.commit 方法:

store.commit('increment')

提交载荷(Payload):

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

其中,第一个参数是state,后面的参数是向 store.commit 传入的额外的参数,即 mutation 的 载荷(payload)。

store.commit方法的第一个参数是要发起的mutation类型名称,后面的参数均当做额外数据传入mutation定义的方法中。

规范的发起mutation的方式如下:

// 以载荷形式
store.commit('increment'{
    
    
  amount: 10   //这是额外的参数
})

// 或者使用对象风格的提交方式
store.commit({
    
    
  type: 'increment',
  amount: 10   //这是额外的参数
})

额外的参数会封装进一个对象,作为第二个参数传入mutation定义的方法中。

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

4、Actions

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

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

Actions中的方法有两个默认参数:
1.context上下文(相当于箭头函数中的this)对象。
2.payload挂载参数。

因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。

actions: {
    
    
  increment ((context,payload)) {
    
    
    context.commit('increment')
  }
}

在action内部执行异步操作:

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

在组件中调用:

this.$store.dispatch('incrementAsync ',10)
// 以对象形式分发Action
store.dispatch({
    
    
  type: 'incrementAsync',
  amount: 10
})

Actions 支持同样的载荷方式和对象方式进行分发。

由于是异步操作,所以我们可以为我们的异步操作封装为一个Promise对象:

    incrementAsync (context,payload){
    
    
        return new Promise((resolve,reject)=>{
    
    
            setTimeout(()=>{
    
    
                context.commit('increment',payload)
                resolve()
            },2000)
        })
    }

现在可以写成:

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

Action与Mutation的区别:
Action 类似于 mutation,不同在于

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

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

组件内调用模块a的状态:

this.$store.state.a

而提交或者dispatch某个方法和以前一样,会自动执行所有模块内的对应type的方法:

this.$store.commit('increment')
this.$store.dispatch('incrementAsync ')

嵌套子模块:
首先创建子模块的文件:

// 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
}

然后在总模块中引入:

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

export default new Vuex.Store({
    
    
  modules: {
    
    
    products   // 添加进模块中
  }
})

模块中的细节:

1.模块中mutations和getters中的方法接受的第一个参数是自身局部模块内部的state

models:{
    
    
    a:{
    
    
        state:{
    
    count:1},
        mutations:{
    
    
            editKey(state){
    
    
                state.count= 2
            }
        },
    }
}

2.getters中方法的第三个参数是根节点状态

models:{
    
    
    a:{
    
    
        state:{
    
    count:1},
        getters:{
    
    
            getCount(state,getter,rootState){
    
    
                return  rootState.count+ state.count
            }
        },
        ....
    }
}

3.actions中方法获取局部模块状态是context.state,根节点状态是context.rootState

models:{
    
    
    a:{
    
    
        state:{
    
    count:5},
        actions:{
    
    
            incrementAsync (context){
    
    
                if(context.state.count=== context.rootState.count){
    
    
                    context.commit('increment')
                }
            }
        },
        ....
    }
}

模块的目录结构:

如果把整个store都放在index.js中是不合理的,所以需要拆分。比较合适的目录格式如下:

store:.
│  actions.js
│  getters.js
│  index.js
│  mutations.js
│  mutations_type.js   ##该项为存放mutaions方法常量的文件,按需要可加入
│
└─modules
        Astore.js

参考:
https://www.jianshu.com/p/2e5973fe1223
https://segmentfault.com/a/1190000019077663

猜你喜欢

转载自blog.csdn.net/weixin_44019523/article/details/113957022