Vue之Vuex使用

上篇已经简单介绍了vuex的部署~这篇就讲下Vuex的简单使用吧

store已经挂载在App Vue根组件~因此就可以像在组件中使用router一样使用store:

获取state中某个属性:this.$store.state.name (name为所需的属性key)

执行一个commit(mutations中的方法):this.$store.commit('name')  mutations中所定义的名字

执行一个dispatch(就是action中的方法):this.$stotre.dispatch('name') action中所定义的名字

执行一个getter:this.$store.getter.name,类似于state,主要做的是一些数据格式化处理~ 


在项目中的使用也就是如下啦~~

state一般都会写在computed属性中啦~,getter就相当于一个vuex的computed

computed:{
 loading(){
  return this.$store.state.loadingStatus
 }
},
created() {
   this.$stroe.commit('SET_BTNSTYLESBG')
  this.$store.dispatch('getBookId')

}

getter的用法也是类似的了~
但是在一些组件中需要引入很多的state状态值以及共享数据,甚至一些commit操作的时候,感觉太麻烦了!~有没有一些简单便捷的方法?
答案是当然有的啦~辅助函数!vuex官方文档有写 ~极大程度的提高了开发效率~

state,getter,mutatios,actions每一个都有一个相应的辅助函数~下面就详细说上一说

一般有两种方法

import { mapState, mapMutations, mapGetters,mapAction } from ‘vuex’

或者 import * as types from ‘vuex’

 第二种是我喜欢的风格~简单看着舒服~不过第一种看着更加直接一些!

需要写的位置依旧不变~只是使用方法稍加变化~!

computed: ...typesState(['name', 'userInfo'])

getter的使用跟上面state的一样~

created() {

    this.name //就是state中的那么属性值!

}

在Vuex有说道,所有正常的状态改变都必须通过commit来进行提交!(所以不要妄图去直接修改state中的属性~这样也许在非严格模式下是可以的~但是一旦出了问题,脑壳儿疼的,因为你会找不到你在哪里做了操作!)

methods:{

/*这里就是mutation与action放的位置了*/

    ...types.mapMutations(['a', ''b])

    ...types.mapAction(['c', 'd'])    

    上述写法也可以修改为一下形式:

    ...types.mapMutations({

        'commitA': 'a'

        'commitB': 'b'

    })

    ...types.mapAction({

        'actoinC': 'c',

        'actionD':'d'

    })

}

这种写法相当于将commitA 映射为a,actionC映射为c,使用是可以直接进行替换~

mounted: {

    /*data就是commit时候所提交的数据,这是使用我们在methods中引入的action,mutation方法了*/

    this.a(data)      ------------------------------- this.commitA(data)

    this.c(data) -------------------------------  tihs.actionC(data)

}

是不是瞬间觉得简单了很多呢~

猜你喜欢

转载自blog.csdn.net/qq_39480597/article/details/79620697