vuex核心概念
state 数据源,载体
getters 用于改变state的值,派生出多个数据源
mutation 唯一可以提交可以改变state的状态,也就是数据的属性值
actions 提交的是mutation,用commit提交 而不是直接变更状态,可以包含任意异步出操作
modules 拆分成多个模块
state
通过计算属性改变值
computed:{
count(){
//定义语法
return this.$store.state.count
}
}
通过getters可以派生出一些新的状态
const store =new Vuex.Store({
state:{
//需要的数据源
todos:[
{id:1,text;'...',done:true},
{id:2,text;'...',done:true},
]
},
//通过此方法对todos数据源进行过滤,拿到新的数据源赋值给doneTodos
getters:{
doneTodos:state=>{
return state.todos.filter(tod0=>todo.done)
}
},
})
mutations
更改Vuex的store中的状态的唯一方法,也只能通过mutations去改变值
const store=new Vux.Store({
state:{
count:1
},
mutations:{
//随便自定义一个函数,参数是默认state
add(state){
//通过state.count拿到count属性值在进行自增
state.count++
}
},
actions:{
add(context){
//通过commit的方法提交一个add,这时就会调用mutation中的add方法就会加加1
context.commit("add")
}
}
})
如何改变状态,在需要用到组件中可以随意定义一个方法,比如
methods:{
myAdd(){
this.$store.commit("add") //参数是mutations里面的add方法,通过commit提交后可以触发count++
}
}
modules
当需要管理的状态比较多时,我们需要将vuex的stroe对象分割成模块
const moduleA={
state:{},
mutations:{},
actions:{},
getters:{},
}
const moduleB={
state:{},
mutations:{},
actions:{},
getters:{},
}
const store =new Vuex.Store({
modules:{
a:moduleA,
b:moduleB
}
})
大致流程:组件中通过dispatch去触发actions定义的函数->接着actions通过commit去提交mutations然后去改变state值
在实时去渲染组件
实际项目中用法
const store=new Vuex.Store({
state:{
token:'',
name:'',
},
getters:{
username(state){
return state.name +'你好';
}
},
mutations:{
//第一个参数是默认数据源,第二个参数是自定义的参数
myadd(state,token){
//通过state.token拿到state里面的token属性
state.token=token
},
myname(state,name){
state.name=name
}
},
actions:{
//在组件中用dispatch进行触发调用
add(state){
//可以直接在actions里面用commit提交到mutations进行改变
state.commit('myadd')
}
}
})
在组件中用法
methods:{
indexAdd(){
//用commit进行提交把123赋值给token
this.$store.commit("myadd",123);
this.$store.commit("myname","zhangsan");
this.$store.dispatch('add');
this.$store.getters.username;
}
}
如何拆分开写
分别建立 state mutations actions getters 文件
在state.js文件中
export default{
count:1
}
在mutations.js文件中
export default{
add(state,num){
state.count=num
}
}
在store.js中
import defaultState from './state'
import mutations from './mutations'
export default()=>{
return new Vuex.Stroe({
state:defaultState,
mutations
})
}
store中的监听事件
store.watch((state)=>state.count+1,(newcount){
console.log(newcount)
})