您现在的位置是:网站首页> 编程资料编程资料
vue中复用vuex.store对象的定义_vue.js_
2023-05-24
488人已围观
简介 vue中复用vuex.store对象的定义_vue.js_
复用vuex.store对象的定义
我有几个组件,都需要用到vuex.store,而且这几个组件结构极其类似,就在想,能不能复用store的对象定义?因为每个组件都定义一遍,繁琐,且没必要。
主要是用到克隆组件。具体代码如下:
1. 共用的store定义
/src/store/common.js
export default { namespaced: true, state: { v: "hello store", // for test items: [], }, getters: { v: (state) => state.v, items: (state) => { return state.items; }, }, mutations: { // 同步操作 setV(state, val) { state.v = val; }, setItems(state, val) { state.items = val; }, }, actions: { keepItems: ({ commit }, val) => { commit("setItems", val); }, }, };2. 组件1
/src/store/component1.js
import cloneDeep from "lodash/cloneDeep"; import common from "./common"; const category = cloneDeep(common); export default component1;
3. 组件2
/src/store/component2.js
import cloneDeep from "lodash/cloneDeep"; import common from "./common"; const category = cloneDeep(common); export default component2;
vuex中的store
1. Vuex是什么
在了解Store之前,我们先来看看Vuex是个什么东西。Vuex本质上就是一个Vue.js的插件,是用于对复杂应用进行状态管理用的,打印Vuex以后输出:
{ Store: function Store(){}, mapActions: function(){}, // 对应Actions的结果集 mapGetters: function(){}, // 对应Getters的结果集 mapMutations: function(){}, // 对应Mutations的结果集 mapState: function(){}, // 对应State的结果集 install: function install(){}, installed: true }Vuex和单纯的全局对象有以下两点不同:
- Vuex的状态存储是响应式的。当Vue 组件从 Store 中读取状态的时候,若 Store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
- 不能直接改变 Store 中的状态。改变Store 中的状态的唯一途径就是显式地提交 mutation。
2. Store
每一个Vuex应用的核心就是Store(仓库),我们可以说Store是一个容器,Store里面的状态与单纯的全局变量是不一样的,无法直接改变Store中的状态。想要改变Store中的状态,只有一个办法,显式地提交mutation。
3. 一个完整的Store结构
const store = new Vuex.Store({ state: { // 存放状态 }, getters: { // state的计算属性 }, mutations: { // 更改state中状态的逻辑,同步操作 }, actions: { // 提交mutation,异步操作 }, // 如果将store分成一个个的模块的话,则需要用到modules。 //然后在每一个module中写state, getters, mutations, actions等。 modules: { a: moduleA, b: moduleB, // ... } });4. 状态管理的几个核心概念
1. state
state是状态数据,可以通过this.$store.state来直接获取状态,也可以利用vuex提供的mapState辅助函数将state映射到计算属性(computed)中去。用data接收的值不能及时响应更新,用computed就可以:
export default { data () { return { dataCount: this.$store.state.count //用data接收 } }, computed:{ count(){ return this.$store.state.count //用computed接收 } } }mapState 辅助函数:
mapState是state的语法糖,当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:
// 在单独构建的版本中辅助函数为 Vuex.mapState import { mapState } from 'vuex' export default { // ... computed: mapState({ // 箭头函数可使代码更简练 count: state => state.count, // 传字符串参数 'count' 等同于 `state => state.count` countAlias: 'count', // 为了能够使用 `this` 获取局部状态,必须使用常规函数 countPlusLocalState (state) { return state.count + this.localCount } }) }当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
computed: mapState([ // 映射 this.count 为 store.state.count 'count' ])
2. getter
getters本质上是用来对状态进行加工处理。Getters与State的关系,就像Vue.js的computed与data的关系。getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。可以通过this.$store.getters.valueName对派生出来的状态进行访问。或者直接使用辅助函数mapGetters将其映射到本地计算属性中去。
mapGetters 辅助函数:
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:
import { mapGetters } from 'vuex' export default { // ... computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }mapGetters实际上是一个方法Vuex对象上的一个方法,这从本文开头打印的那个Vuex对象的内容可以看出来。…这个符号是ES2015的一个新的语法糖,即将mapGetters处理后的内容展开后填入。
如果你想将一个 getter 属性另取一个名字,使用对象形式:
mapGetters({ // 映射 `this.doneCount` 为 `store.getters.doneTodosCount` doneCount: 'doneTodosCount' })
3. mutation
mutations的中文意思是“变化”,利用它可以更改状态。事实上,更改 Vuex 的 store 中的状态的唯一方法就是提交 (commit)mutation。不过,mutation触发状态改变的方式有一点特别,所谓commit一个mutation,实际是像触发一个事件一样,传入一个mutation的类型以及携带一些数据(称作payload,载荷)。
mutations: { //放置mutations方法 increment(state, payload) { //在这里改变state中的数据 state.count = payload.number; } },那commit一个mutation在代码层面怎么表示呢?
this.$store.commit('increment', { amount: 10 }) //或者这样 this.$store.commit({ type: 'increment', amount: 10 })除了这种使用 this.$store.commit('xxx') 提交 mutation的方式之外,还有一种方式,即使用 mapMutations 辅助函数将组件中的 methods 映射为 this.$store.commit。例如:
import { mapMutations } from 'vuex' export default { // ... methods: { ...mapMutations([ 'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')` // `mapMutations` 也支持载荷: 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)` ]), ...mapMutations({ add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')` }) } }经过这样的映射之后,就可以通过调用方法的方式来触发其对应的(所映射到的)mutation commit了,比如,上例中调用add()方法,就相当于执行了this.$store.commit('increment')了。
考虑到触发的mutation的type必须与mutations里声明的mutation名称一致,比较好的方式是把这些mutation都集中到一个文件(如mutation-types)中以常量的形式定义,在其它地方再将这个文件引入,便于管理。而且这样做还有一个好处,就是整个应用中一共有哪些mutation type可以一目了然。就像下面这样:
// mutation-types.js export const SOME_MUTATION = 'SOME_MUTATION' // store.js import Vuex from 'vuex' import { SOME_MUTATION } from './mutation-types' const store = new Vuex.Store({ state: { ... }, mutations: { // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名 [SOME_MUTATION] (state) { // mutate state } } })
4. action
action可以提交mutation,在action中可以执行store.commit,而且action中可以有任何的异步操作:
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit('increment') } } })或者用ES2015的参数解构,可以简写成:
actions: { increment ({commit}) { commit('increment') } }和mutation类似,我们像上面这样生命action的处理函数。它接收的第一个参数是一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。
不过,mutation处理函数中所做的事情是改变state,而action处理函数中所做的事情则是commit mutation。
怎么触发action呢?按照Vuex的叫法,这叫分发(dispatch),我们反正知道它实际上是触发的意思就行了。具体的触发方法是this.$store.dispatch(actionType, payload)。所传的两个参数一个是要触发的action的类型,一个是所携带的数据(payload),类似于上文所讲的commit mutation时所传的那两个参数。具体如下:
// 以载荷形式分发 this.$store.dispatch('incrementAsync', { amount: 10 })或
// 以对象形式分发 this.$store.dispatch({ type: 'incrementAsync', amount: 10 })还有一种方法是使用 mapActions 辅助函数将组件的 methods 映射为 this.$store.dispatch 调用。如下:
import { mapActions } from 'vuex' export default { // ... methods: { ...mapActions([ 'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')` // `mapActions` 也支持载荷: 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)` ]), ...mapActions({ add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')` }) } }另外,还需要知道, this.$store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 this.$store.dispatch 仍旧返回 Promise。
再来看一些组合性的异步操作:
actions: { actionA ({ commit }) { return new Promise((resolve, reject) => { setTimeout(() => { commit('someMutation') resolve() }, 1000) }) } }现在你可以:
$this.store.dispatch('actionA').then(() => { // ... })在另外一个 action 中也可以:
actions: { // ... actionB ({ dispatch, commit }) { return dispatch('actionA').then(() => { commit('someOtherMutation') }) } }最后,如果我们利用 async / await 这个 JavaScript 即将到来的新特性,我们
相关内容
- Vite打包分割代码的详细过程记录_vue.js_
- Vue实现无限级树形选择器_vue.js_
- vue对象的深度克隆方式_vue.js_
- Vue uni-app以H5模式引入Jquery配置教程_vue.js_
- ES6字符串和数值新增方法总结_javascript技巧_
- vue对象复制方式(深拷贝,多层对象拷贝方式在后面)_vue.js_
- JS组件封装之监听localStorage的变化_javascript技巧_
- 关于iview按需引用后使用this.$Modal报错的解决_vue.js_
- 微信小程序实现简单秒表设计_javascript技巧_
- 微信小程序实现答题倒计时_javascript技巧_
