Vuex是什么
vuex是一个专门为vue.js应用程序开发的状态管理模式。
vuex安装
cnpm install vuex -S
vuex store
vuex中的核心模块 可以理解为一个仓库 或者说是一个存放数据的总部
store的特点
共享 组件与组件之间的数据都是共享的
响应式
创建一个store
import 'Vuex' from vue
vue use(Vuex)
const store = new Vuex.store({
state:{
count:0
},
mutations:{
increment(state){
state.count++
}
}
})
1.state
state是用来存放组件之间共享的数据,一般会在组件的计算属性中获取state的数据
使用方法 this.
s
t
o
r
e
.
s
t
a
t
e
变
更
s
t
a
t
e
的
值
:
通
过
提
交
一
个
m
u
t
a
t
i
o
n
:
t
h
i
s
.
store.state 变更state的值:通过提交一个mutation :this.
store.state变更state的值:通过提交一个mutation:this.store.commint(“change”,payload)
mutation下的函数接收state作为参数,解收一个payload(载荷)作为第二个参数,payload是用来记录开发者使用改函数的一些信息如提交的数据 payload一般为对象格式
注:mutation为同步方法
代码演示
var myStore = new Vuex.stroe({
state:{
//用来存放组件之间共享的数据
name:"xiarongwu",
age:18,
Id:1
},
mutations:{
//显示更改state里的数据
change(state,a){
state.num+=a
}
}
});
//自定义一个组件
vue.component('hello',{
template:`<p @click="changeNum">姓名:{{name}}<p>`
computed:{ //计算属性
name(){
return this.$store.state.name
},
age(){
return this.$store.state.age
},
num(){
return this.$store.state.num
}
},
mounted(){
console.log(this)
},
methods:{
changeName(){
//在组件里提交
//this.name++,
this.$store.commit('change',10)
}
}
})
2.getters
getters可以看作是store的计算属性
vuex允许我们在store中定义“getter”,就像计算属性一样,getter的返回值会根据它的依赖被缓存起来,且只有当他的依赖值发生了改变才会被重新计算,具体的演示代码就不写了官方文档里就有很好理解
3.mutation
什么是mutation?
通俗来说mutation里面装着一些改变数据方法的集合,vuex就是吧处理数据逻辑方法全部放在mutation里面,使得数据和视图分离
注意 vuex中改变store的唯一方法就是mutation 不要用乱七八糟的偷懒方法 会导致代码维护极其困难
如何使用mutation
每一个mutation都有一个字符串类型的事件(type)和回调函数(handler)这和订阅发布有点类似 先注册事件 当触发响应类型的时候调用handker() 调用type的时候需要用到store.commit
//store.js
const store = new Vuex.store({
state:{
count:1
},
mutations:{
/注册事件type:increment,handler 第一个参数为state
increment(state){
//变更状态 ++
state.count++
}
},
//在自定义组件中触发该事件
<template>
<button @click="increment"><button>
</template>
<script>
export default{
methods:{
increment(){
this.$store.commit('increment')
}
}
}
</script>
})
4.Action
类似于mutation 但是mutation只能处理同步的函数,而action则是可以处理任何的异步操作
作用 异步的更改状态,action并不直接改变state,而是发起mutation
注意:action改变state里的值也不能直接改变 也要用在mutation里修改
代码演示
state:{
msg:'hellp'
},
mutation:{
getChangeMsg(state,payload){
state.msg=payload
}
},
action:{
getOfAjax(store){
settimeout(()=>{
store.commit(getChangeMsg,'hello world')
},1000)
}
}
5.Moudle
作用:将store分割成模块
由于使用单一状态树,应用的所有状态会集中到一个比较打的对象。当应用变成非常复杂是,store对象就变得相当臃肿
因此为了解决此问题我们使用Mould将store分割成许多个模块,每个模块都拥有自己的state mutation action getter