一、vuex原理
简单来说: 对 vue 应用中多个组件的共享状态进行集中式的管理(读/写) ,vuex是vue的一个插件

vuex的四个配置对象:
state:数据源
getters:计算属性(但只能get,set的话要通过组件里面写代码dispatch之类的)
actions:组件里面使用dispatch调用action,可以执行异步操作
const actions = {
zzz ({commit, state}, data1) {
commit('yyy', {data1})
}
}
mutations:action commit mutation,mutation直接操作数据,不能写异步代码
const mutations = {
yyy (state, {data1}) {
// 更新 state 的某个属性
}
}

二、vuex的使用
1.准备工作
npm install vuex --save
src下建立store文件夹(弄成一个单独的模块),文件夹下建index.js(引用vue和vuex,Vue.use(Vuex)使用插件vuex,export default new一个vuex.store对象),state.js,actions.js,mutations.js,getters.js,mutaions-type.js(放mutation的常量函数名,注意在mutations中使用时 [ ] 把函数名框起来表明是变量不是字符串)
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
整个项目(即src文件夹下)的main入口js里importstore,并且在vue中配置对象store
import store from './store'
new Vue({
store
})
2.在组建中使用
1) 当在vue中配置了store,所有用 vuex 管理的组件中都多了一个属性$store, 它就是一个 store 对象,这个对象有:
属性: state: 注册的 state 对象,getters: 注册的 getters 对象
方法: dispatch(actionName, data): 分发调用 action
this.$store.dispatch('actionname',data)
this.$store.state.dataname
this.$store.getters.computedname
2) 可以在组建中使用映射函数简化编码(不直接使用$store),要求就是组件中的变量名和函数名都要和vuex中的一致(一般),不一致的话要有映射关系
mapState等函数返回一个对象
import {mapState, mapGetters, mapActions} from 'vuex'
export default {
computed: { //vuex里的state/getters都写在这个computed里面,映射以后可以用watch深度监视
...mapState(['xxx']), //把数组换成对象可以名称不一样{xxx:‘xxxVuex’}
...mapGetters(['mmm']),
}
methods: mapActions(['zzz'])
}
{{xxx}} {{mmm}} @click="zzz(data)"
三、优化
当state里面的数据过多的时候还可以分模块
在store文件夹下创建一个modules文件夹,里面是以statename命名的js,每个js包含了state和与这个state相关的所以actions、getters、mutations.最后在vuex.store对象里面配置

export default new Vuex.Store({
actions,
getters,
modules: {
cart,
products
}
})
四、render
在main.js入口里的vue还可以这样写
new Vue({
el:'#app',
render: h=>h(App) //这句代替了component:{App} 和template:‘<App/>’
’})
render 配置的写法相当于:
function(createElement){
return createElement(App
}
说明render函数是用来创建标签的