Vuex数据设计和实现

Vuex是项目中数据共享的重要组成部分,本文章总结个人在项目中使用Vuex的使用方法。

  1. 设置项目目录src/store
    在这将actions,getters,mutations,state,单独抽象成一个文件进行管理。为了使mutation看起来更加简洁明了,将mutation-types也分割出来统一管理。
├──  store
    ├── index.js          # 我们组装模块并导出 store 的地方
    ├── state.js      # 根级别的 states  
    ├── getters.js      # 根级别的 getters
    ├── actions.js        # 根级别的 action
    ├── mutations.js      # 根级别的 mutation
    └── mutation-types.js      # mutation类型
  1. index.js
import Vue from 'vue'
import Vuex from 'vuex'
import * as mutations from './mutations'
import * as actions from './actions'
import state from './state'
import createLooger from 'vuex/dist/logger' // 在没有装vue-devtools的情况下可以使用,在控制台会打印出state前后状态变化

Vue.use(Vuex)
const debug = process.env.NODE_ENV === 'production'

export default new Vuex.store({
	state,
	mutations,
	actions,
	getters,
	strict: debug,  // 开发环境下开启严格模式,任何不是由mutation引起更改state的操作都会抛出错误,确保在发布环境下关闭严格模式,以避免性能损失。
	plungins:  debug ? [createLogger()] : []  // 开发环境下开启
})

  1. state.js
    设置全局共享的数据,举个例子如下:
export default state = {
	userName: '',
	stationList: [],
	station: {}
}
  1. getters.js
    Vuex允许在store中定义getter,可以认为是store的计算属性。当值改变时也会重新计算。
    getter接收state作为其第一个参数。
export const userName = state => state.userName
export const stationList = state => state.stationList
export const station = state => state.station

由于Vuex的状态存储是响应式的,因此在使用数据时可以利用计算属性从store实例中读取数据。

import { mapGetters } from 'vuex
computed: {
	...mapGetters([
		name: 'userName',
		'stationList',
		'station'
	])
}
  1. actions.js
    Action用于提交Mutation,而不直接修改状态。
import * as types from './mutation-types'
export const selectStation = function({ commit, state }, param) {
	if(state.stationList.length === 0) {
		commit(types.SELECT_STATION, param)
	}
}

使用Action时需要从methods中使用。

import { mapActions } from 'vuex'
methods: {
	...mapActions([
		'selectStation'
	]),
	_changeStation(station) {
		this.selectStation(station)
	}
}
  1. mutations.js
import * as types from './mutation-types'
export mutations = {
	[types.SELECT_STATION](state, param) {
		state.station = param
	}
}
  1. mutation-types.js
    使用常量替代 mutation 事件类型在各种 Flux 实现中是很常见的模式。这样可以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然:
export const SELECT_STATION = 'SELECT_STATION'

https://github.com/Gesj-yean/vue-demo-collection 记录了更多优秀插件的使用方法。有时间的同学请看我的置顶博客,可太感谢啦。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值