Vue2教程详解七(Vuex3)

目录

简介

安装与使用

核心概念 

Store

State

Actions

Mutations

Actions和Mutations的区别

Getters

辅助函数mapState/mapGetters/mapActions/mapMutations

mapState

mapGetters

mapsMutations

mapActions

Modules

命名空间

在带命名空间的模块内访问全局内容

在带命名空间的模块注册全局action

带命名空间的绑定函数

项目结构


简介

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

该状态自管理应用包含以下几个部分:

  • state,驱动应用的数据源;
  • view,以声明方式将state映射到视图;
  • actions,响应在view上的用户输入导致的状态变化。

以上,就是一个表示“单向数据流”理念的简单示意,但是当我们的应用遇到多个组件共享状态时,单项数据流的简洁性就会很容易被破坏:

  • 多个视图依赖于同一状态。
  • 来自不同视图的行为需要变更同一状态

对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递也无能为力。

对于问题二,经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码。

所以将组件的共享状态抽取出来,利用全局单例模式管理。在这种模式下,组件树构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或者触发行为!

安装与使用

npm install vuex // vuex安装
import Vuex from 'vuex' // vuex引入

由于Vuex是一个插件,因此要使用

Vue.use(Vuex) // 应用vuex插件

注意:在vue2中,要使用vuex3版本;在vue3中,要使用vuex4版本

核心概念 

Store

Vuex通过store选项,提供了一种机制将状态从跟组件“注入”到每一个子组件中;

const app = new Vue( {
    el: '#app',
    // 把store对象提供给“store”选项,这可以把store的实例注入所有的子组件
    store,
    data: {
        return{
        
        }
    }
})

使用的时候使用this.$store,store中包含state/action/mutations

State

State用于存储数据(状态)

如在项目中创建一个store文件夹和index.js文件,并定义state中sum变量为0,组件中读取state中的值使用$store.state.xxx,如此处$store.state.sum

// 该文件用于创建Vuex中最核心的store
// 引入Vuex
import Vuex from "vuex";
// 应用Vue插件
Vue.use(Vuex)
// 准备state,用于存储数据
const state = {
    sum:0 // 定义sum变量为0
}

// 创建store
const store = new Vuex.store({
    state
})

// 暴露store
export default store

并在main.js文件中引入store

import store from '../../iot-vue/store/index'

Vue.config.productionTip = false
Vue.use(element)

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    components: { App },
    template: '<App/>',
    store
})

Actions

actions可用于响应组件中用户的动作(指令)

示例:定义actions响应用户的相加操作

// 该文件用于创建Vuex中最核心的store
// 引入Vuex
import Vuex from "vuex";
// 应用Vue插件
Vue.use(Vuex)
// 准备state,用于存储数据
const state = {
    sum:0
}
const actions = {
    // 响应组件中用户操作相加的动作(指令)
    addData(context,value) {
        context.commit('increment',value)
    }
}
// 创建store
const store = new Vuex.store({
    state,
    actions
})

// 暴露store
export default store

actions中默认带有一个参数为context,即上下文信息,里面内置有一些vue觉得你可能会用到的信息~当然,也可传入额外的参数。context.commit用于将要调用的方法传给mutations,其中第一个传参要对应mutations中的某个方法;

Actions 也支持载荷方式(载贺即参数)和对象方式进行分发:

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

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

Mutations

mutations才是操作数据真正的方法,其中默认传参state,则可方便对数据进行操作,亦可传入额外的参数,如value

// 该文件用于创建Vuex中最核心的store
// 引入Vuex
import Vuex from "vuex";
// 应用Vue插件
Vue.use(Vuex)
// 准备state,用于存储数据
const state = {
    sum:0
}
const actions = {
    // 响应组件中用户操作相加的动作(指令)
    addData(context,value) {
        context.commit('increment',value)
    }
}
const mutations = {
    // 真正执行相加操作
    increment(state,value) {
        state.sum += value
    }
}
// 创建store
const store = new Vuex.store({
    state,
    actions,
    mutations
})

// 暴露store
export default store

当mutation中的动作结束后,就会重新修改state中的数值,并不断循环这些动作state-actions-mutations-state;

在大多数情况下,commit的载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:

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

store.commit('increment', {
  amount: 10
})

 提交 mutation 的另一种方式是直接使用包含 type 属性的对象:

store.commit({
  type: 'increment',
  amount: 10
})

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

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

使用常量替代 Mutation 事件类型

使用常量替代 mutation 事件类型在各种 Flux 实现中是很常见的模式。这样可以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然:

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import { createStore } from 'vuex'
import { SOME_MUTATION } from './mutation-types'

const store = createStore({
  state: { ... },
  mutations: {
    // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    [SOME_MUTATION] (state) {
      // 修改 state
    }
  }
})

Actions和Mutations的区别

通过上面的讲解,感觉actions其实并没有啥用,只是起到了将要调用的mutations方法传递作用,那是否可以直接通过调用mutations方法呢?并且actions的作用到底体现在哪里呢?

  • 首先回答第一个问题,是否可以直接调用mutaitons方法呢?

答案当然是可以的,如果要使用的场景正如前面所述,只是起到一个传递mutation方法的作用,并没有特殊的处理,则可以跳过中间的actions,直接调用mutations方法,直接使用this.$store.commit('xxxx')即可

  • 其次回答第二个问题,actions的作用在哪里?

actions与mutaions的不同之处在于:

actions提交的是mutations,而不是直接变更状态;

actions可以包含任意异步操作;而mutations必须执行同步函数,因为当mutaion触发的时候,回调函数还没有被调用;

而在actions内部可执行异步操作,用于处理网络请求或业务逻辑,

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

    }
}

使用$store.dispatch('方法名',其它参数)方式触发action方法

store.dispatch('incrmentAsync', 10)

Getters

当state中的数据需要经过加工后再使用时,可以使用getters加工,它可以认为是store的计算属性,所以要以返回值的形式使用,且只有当它的依赖值发生了改变才会被重新计算;getters接收state作为其第一个参数,也可以接收其他getter作为第二个参数;

示例:将state中sum值放大10倍使用

// 在store/index.js文件中配置getters
const getters = {
    multifySum(state){
        // 将sum值放大十倍
        return state.sum * 10
    }
}
// 创建store
const store = new Vuex.store({
    state,
    actions,
    mutations,
    getters
})

在组件中读取数据:

$store.getters.multifySum

辅助函数mapState/mapGetters/mapActions/mapMutations

当然,在使用之前要先引入:

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

mapState

当一个组件需要获取多个状态时,将这些状态都声明为计算属性会有些重复,为解决这个问题,可使用mapState辅助函数帮助生成计算属性:

// 正常写法,多次重写this.$store.state
computed: {
    sum() {
        return this.$store.state.sum
    },
    min() {
        return this.$store.state.min
    },
    max() {
        return this.$store.state.max
    }
}

// 使用mapState生成计算属性(对象写法)
computed: {
    ...mapState({sum: 'sum', min: 'min', max: 'max'})

}

// 当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组(数组写法)
computed: {
    ...mapState(['sum','min','max'])
}

mapGetters

和上述一样,

computed: {
    // 一般写法
    bigSum() {
        return this.$store.getters.bigSum
    }
    // 使用mapGetters的对象形式
    ...mapGetters({bigSum: 'bigSum'})
    // 使用mapGetters的数组形式
    ...mapGetters(['bigSum'])
}

mapsMutations

methods: {
    // 一般写法
    increment() {
        this.$store.commit('add', this.n)
    }
    decrement() {
        this.$store.commit('minus', this.n)
    }
    // 使用mapMutations生成对应的方法(对象写法)
    ...mapMutations({increment: 'add', decrement: 'minus'})
    // 使用mapMutations生成对应的方法(数组写法)
    ...mapMutations(['add','minus'])
}

mapActions

methods: {
    // 一般写法
    increment() {
        this.$store.dispatch('add', this.n)
    }
    decrement() {
        this.$store.dispatch('minus', this.n)
    }
    // 使用mapActions生成对应的方法(对象写法)
    ...mapActions({increment: 'add', decrement: 'minus'})
    // 使用mapActions生成对应的方法(数组写法)
    ...mapActions(['add','minus'])
}

注意: 

mapActions与mapMutations使用时,若需要传递参数需求:在模板中绑定事件时传递好参数,否则参数默认是事件对象event~

Modules

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,当应用变得非常复杂时,store对象就有可能变得相当臃肿;

为解决以上问题,Vuex允许将store分割成模块(module)。每个模块拥有自己的state/mutaition/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 的状态

对于模块内部的mutaiton和getter,接收的第一个参数是模块的局部状态对象state;对于模块内部的getter,根节点状态会作为第三个参数暴露出来;

const moduleA = {
  // ...
  getters: {
    sumWithRootCount (state, getters, rootState) {
      return state.count + rootState.count
    }
  }
}

对于模块内部的action,局部状态通过context.state暴露出来,根节点状态则为context.rootState:

const moduleA = {
  // ...
  actions: {
    incrementIfOddOnRootSum ({ state, commit, rootState }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment')
      }
    }
  }
}

命名空间

默认情况下,模块内部的action/mutation和getter是注册在全局命名空间的,这样使得多个模块能够对同一mutation或action作出响应;

若希望模块具有更高的封装度和复用性,可通过添加namespaced:true的方式使其成为带命名空间的模块。当模板被注册后,它的所有getter/action及mutation都会自动根据模块注册的路径调整命名,如:

const store = new Vuex.Store({
  modules: {
    account: {
      namespaced: true,

      // 模块内容(module assets)
      state: () => ({ ... }), // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
      getters: {
        isAdmin () { ... } // -> getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> commit('account/login')
      },

      // 嵌套模块
      modules: {
        // 继承父模块的命名空间
        myPage: {
          tate: () => ({ ... }),
          getters: {
          profile () { ... } // -> getters['account/profile']
          }
        },

        // 进一步嵌套命名空间
        posts: {
          namespaced: true,
          state: () => ({ ... }),
          getters: {
            popular () { ... } // -> getters['account/posts/popular']
          }
        }
      }
    }
  }
})

启用了命名空间的getter和action会收到局部化的getter,dispatch和commit。换言之,在使用模块内容时不需要在同一模块内额外添加空间名前缀。更改namespaced属性后不需要修改模块内的代码。

在带命名空间的模块内访问全局内容

若希望使用全局state和getter,rootState和rootGetters会作为第三和第四参数传入getter,也会通过context对象的属性传入action。

若需要在全局命名空间内分发action或提交mutation,将{root: true}作为第三参数传给dispatch或commit即可;

modules: {
  foo: {
    namespaced: true,

    getters: {
      // 在这个模块的 getter 中,`getters` 被局部化了
      // 你可以使用 getter 的第四个参数来调用 `rootGetters`
      someGetter (state, getters, rootState, rootGetters) {
        getters.someOtherGetter // -> 'foo/someOtherGetter'
        rootGetters.someOtherGetter // -> 'someOtherGetter'
      },
      someOtherGetter: state => { ... }
    },

    actions: {
      // 在这个模块中, dispatch 和 commit 也被局部化了
      // 他们可以接受 `root` 属性以访问根 dispatch 或 commit
      someAction ({ dispatch, commit, getters, rootGetters }) {
        getters.someGetter // -> 'foo/someGetter'
        rootGetters.someGetter // -> 'someGetter'

        dispatch('someOtherAction') // -> 'foo/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

        commit('someMutation') // -> 'foo/someMutation'
        commit('someMutation', null, { root: true }) // -> 'someMutation'
      },
      someOtherAction (ctx, payload) { ... }
    }
  }
}

在带命名空间的模块注册全局action

若需要在带命名空间的模块注册全局action,可添加root:true,并将这个action的定义放在函数handler中,如:

{
  actions: {
    someOtherAction ({dispatch}) {
      dispatch('someAction')
    }
  },
  modules: {
    foo: {
      namespaced: true,

      actions: {
        someAction: {
          root: true,
          handler (namespacedContext, payload) { ... } // -> 'someAction'
        }
      }
    }
  }
}

带命名空间的绑定函数

当使用mapState/mapGetters/mapActions/mapMutations这些函数来绑定带命名空间的模块时,写起来可能较繁琐;

computed: {
  ...mapState({
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
  })
},
methods: {
  ...mapActions([
    'some/nested/module/foo', // -> this['some/nested/module/foo']()
    'some/nested/module/bar' // -> this['some/nested/module/bar']()
  ])
}

对于这种情况,可将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。于是上面的例子可简化为:

computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
  })
},
methods: {
  ...mapActions('some/nested/module', [
    'foo', // -> this.foo()
    'bar' // -> this.bar()
  ])
}

而且,可以通过使用createNamespacedHelpers创建基于某个命名空间辅助函数。它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数:

import { createNamespacedHelpers } from 'vuex'

const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')

export default {
  computed: {
    // 在 `some/nested/module` 中查找
    ...mapState({
      a: state => state.a,
      b: state => state.b
    })
  },
  methods: {
    // 在 `some/nested/module` 中查找
    ...mapActions([
      'foo',
      'bar'
    ])
  }
}

项目结构

├── index.html
├── main.js
├── api
│   └── ... # 抽取出API请求
├── components
│   ├── App.vue
│   └── ...
└── store
    ├── index.js          # 我们组装模块并导出 store 的地方
    ├── actions.js        # 根级别的 action
    ├── mutations.js      # 根级别的 mutation
    └── modules
        ├── cart.js       # 子模块
        └── products.js   # 另一子模块
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迷糊的小小淘

整理不易,赏点动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值