创建vuex对象:
注册vuex对象实例到main.js
使用状态管理器:
- state属性
作用:用来定义一系列共享数据
// 创建store对象
const store = new Vuex.Store({
state:{ // 用来定义共享数据 组件中使用共享数据:this.$store.state.counter ==>简化写法($store.state.counter)
counter:12,
}
});
// 组件中使用共享数据
<h1>{{msg}}登录系统=={{this.$store.state.counter}}</h1>
//<h1>{{msg}}登录系统=={{$store.state.counter}}</h1> // 简化写法
- mutations属性
作用:用来定义对共享数据修改方法‘
// 创建store对象
const store = new Vuex.Store({
state:{ // 用来定义共享数据 组件中使用共享数据:this.$store.state.counter ==>简化写法($store.state.counter)
counter:12,
},
mutations:{ // 用来定义对共享数据修改方法,这里面定义方法都有一个默认参数,默认参数会将状态对象传递给自定义方法 组件中调用这个方法:this.$store.commit('方法名')
addCounter(state){ // 自定义方法
state.counter += 10
}
}
});
// 组件中使用共享数据
<button @click="addcout">点击+10</button>
methods: {
addcout(){
this.$store.commit('addCounter') // 调用共享管理器中的方法
}
},
方法传参:属性或对象
// 创建store对象
const store = new Vuex.Store({
state:{ // 用来定义共享数据 组件中使用共享数据:this.$store.state.counter ==>简化写法($store.state.counter)
counter:12,
},
mutations:{ // 用来定义对共享数据修改方法,这里面定义方法都有一个默认参数,默认参数会将状态对象传递给自定义方法 组件中调用这个方法:this.$store.commit('方法名')
addCounter(state, aa){ // 自定义方法
state.counter += aa // 如果是个对象:aa.key即可
}
}
});
// 组件中使用共享数据
<button @click="addcout">点击+10</button>
data:{
aa:10
}
methods: {
addcout(){
this.$store.commit('addCounter', this.aa) // 调用共享管理器中的方法
//this.$store.commit('addCounter', {aa:12, bb:22}) // 参数是个对象
}
},
- getters属性
作用:用来书写对共享数据进行计算方法 相当于组件中computed,好处:只计算一次
// 创建store对象
const store = new Vuex.Store({
state:{ // 用来定义共享数据 组件中使用共享数据:this.$store.state.counter ==>简化写法($store.state.counter)
counter:12,
},
mutations:{ // 用来定义对共享数据修改方法,这里面定义方法都有一个默认参数,默认参数会将状态对象传递给自定义方法 组件中调用这个方法:this.$store.commit('方法名')
addCounter(state, aa){ // 自定义方法
state.counter += aa
}
},
getters:{ // 用来定义共享数据的一系列方法:好处只计算一次,缓存结果 组件中使用getters定义的计算属性:this.$store.getters.counterSqrt
counterSqrt(state){ // 这里面定义方法都有一个默认参数,默认参数会将状态对象传递给自定义方法
return state.counter*state.counter // 求平方
}
}
});
// 组件中使用getters中的计算属性
<h1>欢迎{{ msg }}登录员工管理系统==={{$store.state.counter}}--{{this.$store.getters.counterSqrt}}</h1>