40-vue-在根据每个组件中的数据写成vuex时,注意的小点(mapActions、mapGetters、mapState、dispatch()、高级计算属性中的set、get)

1.vuex是全局的,所有组件都可以和它通信。

使用vuex后,与state有关的方法不需要在组件直接在传来传去。

2.getters对象中没有this,应该用getters来取代this

图片示例
在这里插入图片描述

3.高级计算属性(包含get、set)

  组件中get方法对应vuex中的getters对象。
  组件中set方法写成了vuex中的actions。

4.mapState、mapGetters

  mapState:组件中获得state对象中的共享状态。
  mapGetters:组件中获得vuex中的和共享状态有关的计算属性
(例如:假若数组是共享的状态,那数组的长度这个数据就是与数组相关的变量数据)
  mapGetters对象是用来获取vuex组件中的计算属性的。
  写的位置:mapGetters、mapState导入后,…mapState([ ])与…mapGetters({ })在组件中的computed勾子中写;

图片举例
在这里插入图片描述

5.mapActions在methods勾子中写;mapActions是对dispatch方法的包装

//dispatch()
methods:{
    
    
	  clearCompleteTodos() {
    
    
         this.$store.dispatch("clearAllCompleteTodos")
       }
}

//mapActions方法
import {
    
    mapActions} from "vuex"; //写在export default的外面
methods:{
    
    
 ...mapActions(["clearCompleteTodos"])
}

6.dispatch()与mapstate(mapGetters)

①在要改变state对象中共享状态时,使用dispatch()
②只是获取state/getters中的与共享状态有关的变量,使用mapState、mapGetters

猜你喜欢

转载自blog.csdn.net/A_Bow/article/details/114487949
今日推荐