vuex的核心及图示
每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
- Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
- 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
dispatch 传递两个参数
第一个是 执行的什么操作 执行的操作是action里面有的方法 加几 的 加
第二个是 改变的值 改变的值是 加几 的 几
action 方法中 也有两个参数
是 上下文 和 值
一个是dispatch 一个是commit
如果 vue components 要执行好几种操作 一个方法是解决不了的(一个方法仅支持一种操作)他将回去调用action里面的其他方法 所以就用到了 dispatch
Mutations使用方法
mutations方法都有默认的形参:([state][,payload])
- state 是当前VueX对象中的state
- payload 是该方法在被调用时传递参数使用的
Getters
可以 直接对state中的成员加工后传递给外界 需要放在 store 中 需要写返回值
Getters中的方法有两个默认参数
- state 当前VueX对象中的状态对象
- getters 当前getters对象,用于将getters下的其他getter拿来用
当然也有 mapgetters 方法
mapstate
可以将state的属性直接配置 为想要的函数方法
需要返回值
mapstate方法写将由vue 自动解析
computed :{
//手搓写法
he(){
return this.$store.state.xxx
}
big(){
return this.$store.getters.xxxx
}
//mapstate 写法
。。。mapstate({he:‘xxx’})
...mapgetters({ big:'big'}) 方法逻辑在getters中 对象写法
...mapgetters([big])
}
action
由于直接在mutation方法中进行异步操作,将会引起数据失效。所以提供了Actions来专门进行异步操作,最终提交mutation方法。
Actions中的方法有两个默认参数
- context 上下文(相当于箭头函数中的this)对象
- payload 挂载参数
四个map方法的使用
- mapState方法:用于帮助我们映射
state
中的数据为计算属性
computed: {
//借助mapState生成计算属性:sum、school、subject(对象写法)
...mapState({sum:'sum',school:'school',subject:'subject'}),
//借助mapState生成计算属性:sum、school、subject(数组写法)
...mapState(['sum','school','subject']),
},
- mapGetters方法:用于帮助我们映射
getters
中的数据为计算属性
computed: {
//借助mapGetters生成计算属性:bigSum(对象写法)
...mapGetters({bigSum:'bigSum'}),
//借助mapGetters生成计算属性:bigSum(数组写法)
...mapGetters(['bigSum'])
},
- mapActions方法:用于帮助我们生成与
actions
对话的方法,即:包含$store.dispatch(xxx)
的函数
methods:{
//靠mapActions生成:incrementOdd、incrementWait(对象形式)
...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
//靠mapActions生成:incrementOdd、incrementWait(数组形式)
...mapActions(['jiaOdd','jiaWait'])
}
- mapMutations方法:用于帮助我们生成与
mutations
对话的方法,即:包含$store.commit(xxx)
的函数
methods:{
//靠mapActions生成:increment、decrement(对象形式)
...mapMutations({increment:'JIA',decrement:'JIAN'}),
//靠mapMutations生成:JIA、JIAN(对象形式)
...mapMutations(['JIA','JIAN']),
}
备注:mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。
搭建vuex环境
- 创建文件:
src/store/index.js
//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)
//准备actions对象——响应组件中用户的动作
const actions = {}
//准备mutations对象——修改state中的数据
const mutations = {}
//准备state对象——保存具体的数据
const state = {}
//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state
})
- 在
main.js
中创建vm时传入store
配置项
......
//引入store
import store from './store'
......
//创建vm
new Vue({
el:'#app',
render: h => h(App),
store
})
三、规范目录结构
如果把整个store都放在index.js中是不合理的,所以需要拆分。比较合适的目录格式如下:
store:.
│ actions.js
│ getters.js
│ index.js
│ mutations.js
│ mutations_type.js ##该项为存放mutaions方法常量的文件,按需要可加入
│
└─modules
Astore.js
对应的内容存放在对应的文件中,和以前一样,在index.js中存放并导出store。state中的数据尽量放在index.js中。而modules中的Astore局部模块状态如果多的话也可以进行细分。