1、认识vuex,详看官方文档:https://vuex.vuejs.org/zh/guide/state.html
转发自:https://www.jianshu.com/p/a804606ad8e9
1)State概念
state是vuex中的公共状态,可以将state看作所有组件的date,用于保存数组的公共数据
2)Getters概念
getters可以理解为所有组件的computed属性,getters的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
3)Mutations概念
mutations可以理解为所有组件的methods属性,mutations
对象中保存着更改数据的回调函数,该函数名官方规定叫type
, 第一个参数是state
, 第二参数是payload
, 也就是自定义的参数。
注意:调用mutaions中回调函数, 只能使用store.commit(type, payload)
4)Actions概念
actions类似于mutations,不同在于actions提交的是mutations,而不是直接改变其状态;actions可以包含异步操作;actions中回调函数的第一个参数是context,是一个与store实例具有相同属性和方法的对象。
在该方法中dispatch中的minusPriceAsync
这个回调函数
5)Module概念
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
2、写一个vuex demo
目录:
1)index.js和mutations.js不多说
mutation-types.js存储mutations相关的字符串常量
action.js会对mutation做一些封装以及一些异步的操作
state.js管理状态
getters.js获取state做映射
2)以获取singer为例子
state:
const state={
singer:{}
}
export default state
mutation-types:
export const SET_SINGER='SET_SINGER'
mutations:
import * as types from './mutation-types'
const mutations={
[types.SET_SINGER](state,singer) {
state.singer=singer
}
}
export default mutations
getter
export const singer=state=>state.singer
index
import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters'
import state from './state'
import mutations from './mutations'
import createLogger from 'vuex/dist/logger'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
actions,
getters,
state,
mutations,
strict: debug,
plugins: debug ? [createLogger()] : []
})
action暂时用不到
3)在main.js中配置
import store from './store'
new Vue({
el: '#app',
render: h => h(App),
store,
router
})
4)开始给singer传值
import {mapMutations} from 'vuex'
methods:{
...mapMutations({
setSinger:'SET_SINGER'
})}
5)在所需地方获取singer的值
import {mapGetters} from 'vuex'
computed:{
...mapGetters([
'singer'
])
},
created(){
console.log(this.singer)
}