


一、Vuex是甚么
Vuex是同时实现模块自上而下状况(统计数据)管理的一类监督机制,能方便快捷同时实现模块间的统计数据的共享资源。
二、Vuex的益处
① 能在Vuex中INS13ZD共享资源的统计数据,更易合作开发和中后期保护
② 能高工作效率的同时实现模块间的统计资源共享资源,提升合作开发工作效率
③ 储存在Vuex中的统计数据都是积极响应式的,能动态保持统计数据与网页的并行
三、怎样的统计数据适宜储存到Vuex中
通常情况下,多于模块间共享资源的统计数据,才有必要性储存到Vuex中;对组件中的专有统计数据,依然储存在另一方面的data中方可。
四、state
state提供唯一的公共统计数据源,所有共享资源的统计数据都要统一放到State中进行储存。
/*创建store统计数据源,提供唯一公共统计数据*/
const store = new Vuex.Store({
state: { count: 0 }
})
模块中访问State中的统计数据的第一类方式
this.$store.state.自上而下统计数据名称
模块访问State中数据的第二种方式
/*1.从vuex中按需导入mapState函数*/
import { mapState } from vuex
通过刚才导入的mapState函数,将当前模块需要的自上而下统计数据,映射为当前模块的computed计算属性
/*将自上而下统计数据,映射为当前模块的计算属性*/
computed: {
…mapState([count])
}
五、Mutation
Mutation用于变更Store中的统计数据
①、只能通过mutation变更Store统计数据,不能直接操作Store中的统计数据。
②、通过这种方式虽然操作起来稍微繁琐一点,但是能集中监控所有统计数据的变化
触发mutations的第一类方式“this.$store.commit()”
/*定义mutation*/
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
add(state) {
//变更状况
state.count++
}
}
})
//触发mutation
methods:{
btnAdd(){
this.$store.commit(add, step)
}
}
③、触发mutations时传递参数
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
add(state, step) {
//变更状况
state.count += step
}
}
})
触发mutations的第二种方式
1、从vuex中导入mapMutations函数
import { mapMutations } from Vuex
通过刚才导入的mapMutations函数,将需要的mutations函数,映射到methods方法
2、将指定的mutations函数,映射为当前模块的methods函数
methods: {
…mapMutations([add,addN])
}
六、Action
Action用于处理异步任务
如果通过异步操作变更统计数据,必须通过Action,而不能使用Mutation,但是Action中还是要通过触发Mutation的方式变更数据
/*定义Action*/
触发Actions的第一类方式“this.$store.dispatcht()”
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
add(state, step) {
//变更状况
state.count += step
}
},
actions: {
addAsync(context){
setTimeout(() => {
context.commit(add)
},1000)
}
}
})
//触发Action
methods:{
btnAddAsync(){
this.$store.dispatch(addAsync, this.step)
}
}
触发Actions的第二种方式
1、从vuex中导入mapActions函数
import { mapActions } from Vuex
通过刚才导入的mapActions函数,将需要的Actionss函数,映射到methods方法
2、将指定的Actions函数,映射为当前模块的methods函数
methods:{
…mapActions([addAsync,addNAsync ])
}
七、Getter
Getter用于对store中的统计数据进行加工处理形成新的统计数据
①、Getter能对store中的统计数据加工处理之后形成新的统计数据,类似于Vue中的计算属性
②、Store中的数据发生变化,Getter的统计数据也会跟着变化
//定义Getter
const store = newVuex.Store({
state: { count: 0 },
getters:{
showNum: state => {
return: 当前最新的统计数据量是【 + state.count + 】
}
}
})
使用getters的第一类方式
this.$store.getters.名称
使用getters的第二中方式
import { mapGetters } from vuex computed:{
…mapgetters([showNum])
}
举报/反馈