一、介绍
对于vue来说 组件是核心 而一个组件 可分为 view state actions
state是存储该组件的数据 view为ui表现 actions 是用户行为 或者说是改变state的方法
流程 view 发出 actions 然后改变state 之后 view同步state 从而刷新 重新渲染
这无疑是符合 组件的 高内聚 但是 当有多级 组件嵌套 state共享的时候 无疑带来很多问题 中间组件也要传递state 以及管理混乱等等
所以从来提出 vue-x 其类似flux 和redux 简单理解就是 vue只是承担view 把 state 和处理state的action 抽离出来 形成一个store
每个组件上的 state对应为store上的一个节点 从而整个应用也就成为一个 state tree
二、安装(vue脚手架 cli3)
$ vue create
选择 Manually select features 之后选择vue-x
$ cd && npm run serve
三、目录结构
1.根目录多出 store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
}
})
2. 在 main.js 把store.js 导入 并且在实例Vue中传入
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
四、映射store
1. 得到 store里面的数据
在 store.js 里面的state添加 一个属性
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
msg: 'hello world !!' // 添加一个属性
},
mutations: {
},
actions: {
}
})
在about.vue 修改
{{ msg }}
可以看到 about 页面 显示 "hello world !!" 字样
2.修改 store 里面的msg
在about.vue 修改
(1) 在 store 里面 mutations 添加 处理函数
eg: store.js
export default new Vuex.Store({
state: {
msg: 'hello world !!'
},
mutations: {
changeMsg(state){
state.msg = '你好 世界!!'
}
},
actions: {
}
})
(2) 在about.vue 中修改
{{ msg }}
点击改变标题
3. 使用 mapState 映射store
(1) 在about.vue 中修改
{{ msg }}
点击改变标题
或者
computed: mapState(['msg']),
4. getters 对store的state进行处理
eg: store.js
export default new Vuex.Store({
state: {
msg: 'hello world'
},
mutations: {
},
actions: {
},
getters: {
toUpcase: state => {
return state.msg.toUpperCase()
}
}
})
about.vue
mapGetters 使用
eg: about.vue
6.actions
mutations 是state的突变 改变 而 actions提交mutations 而且支持异步操作
eg: store.js
export default new Vuex.Store({
state: {
msg: 'hello world'
},
mutations: {
toUpCase(state){
state.msg = state.msg.toUpperCase()
}
},
actions: {
increment(content){
content.commit('toUpCase')
}
}
})
eg: about.vue