写在前面
有一段时间没有更新掘金了,最近转战有道云笔记,随笔记录一些比较杂的知识点,今天终于有空可以整理一篇关于vuex的介绍文章。内容比较简要,都来自于自己对vuex的梳理理解。比较方便入手即用,对于一些理论性知识概念等不做过多赘述,更详细的还须参照文档使用。
一、概念
vuex适用于vue项目开发时使用的状态管理工具。如果在项目开发中频繁利用组件传参的方式来同步data的值,一旦项目庞大,很难用于管理和维护。
作用:将数据存放在state中,解决了非父子组件的消息传递。减少了AJAX请求次数,有些情景可以直接从内存中的state获取。缺点在于对于此类状态管理工具浏览器刷新时,便会重置state内的数据信息。
二、使用
- 安装
npm install vuex --save - 在src下新建store/index.js
- 初始化index.js
import Vue from 'vue'
import Vuex from 'vuex'
//挂载Vuex
Vue.use(Vuex)
//创建VueX对象
const store = new Vuex({
state:{
//存放的键值对就是所要管理的状态
name:'helloVueX'
}
})
export default store
- 将store挂载到当前项目的Vue实例中去 main.js
new Vue({
el: '#app',
router,
store, //store:store 和router一样,将我们创建的Vuex实例挂载到这个vue实例中
render: h => h(App)
})
- 在组件中可以直接使用
<h1>{{ $store.state.name }}</h1>//组件内
methods:{
add(){
console.log(this.$store.state.name) //组件方法内
}
},
注:此处仅用于vuex值的读取,不建议在组件中直接对state中的成员进行操作,这是因为直接修改(例如:this.$store.state.name = 'hello')的话不能被VueDevtools所监控到。
三、属性介绍
- Mutations操作state数据的方法的集合,对数据进行增删改
-
基本使用: a.携带参数:([state][,payload]) b.state: VueX对象中的state c.payload:在该方法被调用时传递的参数
this.$store.commit('edit',15) //单个值
this.$store.commit('edit',{age:15,sex:'男'}) //对象
this.$store.commit({
type:'edit',
payload:{
age:15,
sex:'男'
}
})
edit(state,payload){ //接收挂载的参数
state.name = 'jack'
console.log(payload) // 15或{age:15,sex:'男'}
}
- 增删state中的成员
Vue.set(state,"age",15) //添加一个age成员
Vue.delete(state,'age') //删除一个成员
-
Getters对state中的成员加工传递给外界 a.state:当前vuex对象中的状态对象 b.getters:当前getters对象,用于将当前的getters下的其他getter拿来用
getters:{
nameInfo(state){
return "姓名:"+state.name
},
fullInfo(state,getters){
return getters.nameInfo+'年龄:'+state.age
}
}
this.$store.getters.fullInfo //组件中调用
- Actions直接在mutation方法中进行异步操作会引起数据失效,提供了Actions专门进行异步操作,最终提交mutation方法
a.context:上下文对象(相当于箭头函数中this)
b.payload:挂载参数
actions:{
aEdit(context,payload){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
context.commit('edit',payload)
resolve()
},2000)
})
}
}
this.$store.dispatch('aEdit',{age:15}) //在组件中调用
- Models 当项目庞大状态比较多时可以使用模块化管理,将store分割成模块,每个模块拥有自己的state、mutation、action、getter
models:{
a:{
state:{},
getters:{},
....
}
}
this.$store.state.a //使用
this.$store.commit('editKey')
this.$store.dispatch('aEditKey')
//提交或者dispatch某个方法和以前一样,
//会自动执行所有模块内的对应type的方法
- 模块中的细节
//模块中mutations和getters中的方法接受的第一个参数是自身局部模块内部的state
models:{
a:{
state:{key:5},
mutations:{
editKey(state){
state.key = 9
}
},
....
}
}
//getters中方法的第三个参数是根节点状态
models:{
a:{
state:{key:5},
getters:{
getKeyCount(state,getter,rootState){
return rootState.key + state.key
}
},
....
}
}
//actions中方法获取局部模块状态是context.state,
//根节点状态是context.rootState
models:{
a:{
state:{key:5},
actions:{
aEidtKey(context){
if(context.state.key === context.rootState.key){
context.commit('editKey')
}
}
},
....
}
}
四、目录规范结构
store:.
│ actions.js
│ getters.js
│ index.js
│ mutations.js
│ mutations_type.js ##该项为存放mutaions方法常量的文件,按需要可加入
│
└─modules
Astore.js
五、图解
