vuex --- vue的几种状态管理模式详细说明

1. 初识vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
父子组件可以使用 $emit 和 props 传递数据,但是如果碰上兄弟组件等需要传递数据时 使用这个就会很繁琐, 这时候 vue就为这些需要频繁使用到的值提供一个统一管理的工具 – vuex,

1.1 安装 vuex

NPM

npm install vuex --save

1.2 使用vuex

初始化 store 下的 index.js 中的内容


import Vuex from 'vuex'

//挂载Vuex
Vue.use(Vuex)

//创建VueX对象
const store = new Vuex.Store({
    state:{
        //存放的键值对就是所要管理的状态
        name:'VueX'
    }
})
export default store

将store 挂载到当前项目的 Vue 实例中去 [ main.js ]

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import VXETable from 'vxe-table'
import ElementUI from 'element-ui'

import '@/permission' // permission control

Vue.use(ElementUI)
Vue.use(global)
Vue.use(VXETable)

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store, // store:store 和router一样 将我们创建的vuex 实例 挂载到 vue 这个实例中 
  render: h => h(App)
}).$mount('#app')

在组件中使用 vuex

加入在 app.vue 中,我们要把state 中 定义的 name 拿来 h1 标签中显示

<template>
    <div id='app'>
        name:
        <h1>{{ $store.state.name }}</h1>
    </div>
</template>

或者要在方法组件中使用

...,
methods:{
    add(){
      console.log(this.$store.state.name)
    }
},
...
  computed: {
    ...mapGetters(['info']),
    device() {
      return this.$store.state.app.device
    }
  },

2. vuex 的核心概念

在 vuex 对象中,不只是有 state ,还有用来操作数据的的方法集, 有默认的五种基本的对象:

  • state: 存储状态(变量)
  • getters: 对数据获取之前的再次编译,可以理解为state的计算属性
  • mutations:更改状态的唯一方法,并且这个过程是同步的。 在组件中使用$store.commit(’ ', params)
  • actions: 异步操作。在组件中使用 $store.dispatch(’’)
  • modules: store的子模块,为了开发大型项目,方便状态管理而使用的

vuex 不限制代码结构,但是规定了一些需要遵守的规则:

  • 应用层级的状态应该集中到单个 store 对象中;
  • 提交 mutation 是更改状态的唯一方法,并且这个过程是同步的;
  • 异步逻辑都应该封装到 action 里面。

2.1 vuex 的工作流程

首先,vue组件如果调用某个vuex的方法过程中需要向后端发送请求 或者是 有异步操作时,需要 dispatch vuex中的actions 方法, 以保证数据的同步。 actions的存在就是为了 让mutations中的方法能在异步操作时起到作用。
如果没有异步操作,那么我们就可以直接在组件内提交状态的 mutations 中自己编写的方法来达到对 state成员的操作。
不建议直接在组件中直接对 state 中的成员进行操作, 这是因为直接修改(例如:this.$store.state.name == ‘hello’)的话不能被VueDevtools 所监控到,最后被修改后的state成员会被渲染到组件的原位置当中去

state,存储数据和状态。
  在js中使用this.$store.state.属性名来获取;
  在元素标签中使用{{$store.state.属性名}}来获取。

2.2 mutations

mutations 是操作 state 数据的方法的集合,比如对该数据的修改、增加、删除等。

mutations 使用方法:

mutations 方法都有默认的行参: ([state],[payload])

  • state 是当前vue对象中的state
  • payload 是该方法在被调用时传递参数使用的

例如,我们编写的方法,当被执行时,能把下例中的name值修改为‘jack’, 我们只需要这样做

index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.store({
	state: {
		name: 'helloVueX'
	},
	mutations: {
		// es6语法, 等同edit: function(){...}
		edit(state){
			state.name = 'jack'
		}
	}
	})
export  default store

而在组件中,我们需要这样去调用这个 mutation – 例如在 App.vue 的某个 method 中:
this.$store.commit(‘edit’)

2.2.1 Mutations 传值

在实际生产过程中,会遇到需要在提交某个 mutation 是需要携带一些参数给方法使用。
单个值提交是:

this.$store.commit('edit', 15)

当需要多参提交时, 推荐把他们放在一个对象中来提交:

this.$store.commit('edit',{ age: 15, sex: '男'})

接收挂载的参数:

edit(state,payload){
	state.name = 'jack'
	console.log(payload) //15 或者 {age: 15, sex: '男'}
}

另一种提交方式:

this.$store.commit({
	type: 'edit',
	payload: {
		age: 15,
		sex: '男'
	}
})

2.2.2 增删 state 中的成员

为了配合Vue 的响应式数据, 我们在 Mutations 的方法中, 应当使用 Vue提供的方法来进行操作。 如果使用 delete 或者 xx.xx = xx 的形式去删或增, 则 Vue 不能对数据进行实时响应。
  • Vue.set 为某个对象设置成员的值,若不存在则新增
    例如对 state 对象中添加一个 age 成员
Vue.set(state, "age", 15)
  • Vue.delete 删除成员
    讲刚刚添加的 age 成员删除
Vue.delete(state, 'age')

2.3 Getters

可以对state 中的成员加工后传递给外界
Getters 中的方法有两个默认参数

  • state 当前Vuex 对象中的状态对象
  • getters 当前getters对象, 用于将getters 下的其他 getter 拿来用
    例如:
getters: {
	nameInfo(state){
		return "姓名:" + state.name
	},
	fullInfo(state, getters){
		return getters.nameInfo + '年龄:' + state.age
	}
}

组件中调用 this.$store.getters.fullInfo

2.4 Actions

由于直接在 mutation 方法中进行异步操作,将会引起数据失效。所以提供了Actions来专门进行一步操作,最终提交 mutation 方法。

Actions 中 的方法有两个默认参数

  • context 上下文(相当于箭头函数中的this)对象
  • payload 挂载参数
    例如,我们在两秒钟后执行 2.1.2 节中的edit 方法
    由于 setTimeout 是异步操作的, 所以需要使用actions
actions: {
	aEdit(context,payload){
		setTimeout(() => {
			context.commit('edit',payload)	
		},2000)
	}
}

在组件中调用: this.$store.dispatch('aEdit', {age: 15})
改进: 由于是异步操作, 所以我们可以为我们的异步操作封装一个Promise对象

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

2.5 modules

当项目庞大,状态非常多时,可以采用模块化管理模式。 Vuex 允许我们将 store 分割成模块(module)。 每个模块拥有自己的 state,mutation,action,getter。 甚至是嵌套子模块 —从上至下进行同样方式的分割。

modules: {
	a: {
		state: {},
		getters: {},
		....
	}
}

组件内调用模块a 的状态: this.$store.state.a
而提交或者dispatch 某个方法和以前一样, 会自动执行所有模块内的对应type方法:

this.$store.commit('editKey')
this.$store.diapatch('aEditKey')

2.5.1 模块的细节

  • 模块中 mutation 和 getter 中的方法接受的第一个参数是自身局部模块内部的 state
modules:  {
	a: {
		state:{key: 5},
		mutations: {
			editKey(state) {
				state.key = 9
			}
		},
		....
	}
}
  • getters中方法的第三个参数是根节点状态
modules: {
	a: {
		state: {key: 5},
		getters: {
			getKeyCount(state, getter, rootState) {
				return rootState.key + state.key
			}
		},
		....
	}
}
  • actions中方法获取局部模块状态是 context.state, 根结点状态是context.rootState
modules: {
	a: {
		state: {key: 5},
		actions: {
			aEditKey(context) {
				if(context.state.key === context.rootState.key){
					context.commit('editKey')
				}
			}
		},
		....
	}
}

3. 规范目录结构

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

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

对应的内容放在对应的文件中,和以前一样,在 index.js 中存放并导出 store。 state中的数据尽量放在index.js 中。 而 modules 中的 Astore 局部模块状态如果多的话 也可以进行细分。

import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    app,
    user,
    tagsView,
    message,
    sysusers,
    setting
  },
  getters,
  // 插件 vuex持久化, 刷新数据自动拉取
  plugins: [createPersistedState({ storage: window.localStorage })]
})

export default store
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值