直击vuex复习V2

70 阅读1分钟

修改store数据为什么一定要使用mutions呢?

因为state是实时更新的,mutations是同步操作,如果直接修改state的话是能够异步操作的,当你异步对state进行操作时,这时候如果state已经在其他地方被修改了,这样就会导致问题。所以state要同步操作,通过mutations的方式限制了异步。

在组件中如何调用store

在模板中

{{ $store.state.count }}

在代码中

在组件中用mutations修改store数据

  mutations: {
    setCount(state:当前store数据, data:新数据) {
      state.count = data
    }
  },

在组件中

  methods: {
    setCount() {
      this.$store.commit('setCount:在mations中定义的函数', 2:要修改的值)
    }
  }

getters

在store的基础上,对数据进行进一步加工得到数据

  getters: {
    updataConut(state) {
      return state.count * 6
    }
  },

actions

异步操作数据,用dispatch调用,函数内可用commit驱动mutations中的方法

  actions: {
    asyncUpDdata(context, params) {
      console.log(context, params)
      /*{getters: {…}, state: {…}, 
      rootGetters: {…}, dispatch: ƒ, commit: ƒ, …},传递的数据*/
    }
  },

在组件中调用

    getAsync() {
      this.$store.dispatch('asyncUpDdata', 1)
    }

modules

拆分模块

获取数据项: {{$store.state.模块名.数据项名}} 
获取getters: {{$store.getters['模块名/getters名']}}

访问模块中的mutations/actions:

  • 如果namespaced为true,则需要额外去补充模块名
  • 如果namespaced为false,则不需要额外补充模块名
$store.commit('mutations名')        // namespaced为false
$store.commit('模块名/mutations名')  // namespaced为true

mapState

映射vuex中store的值 下面例子,如逻辑很多,就会显得很臃肿,接下来引入stateMap改造一下。

  computed: {
    count() {
      return this.$store.state.count
    },
    name() {
      return this.$store.state.name
    },
    age() {
      return this.$store.state.age
    },
    names() {
      return this.$store.state.name + this.$store.state.age
    }
  }

用拓展运算符展开mapState,传入函数。

import { mapState } from 'vuex'

  computed: {
    ...mapState({
    // string 映射 this.count 为 store.state.count的值
      count: 'count',
      // fuction 映射 this.name 为 store.state.name的值
      name: (state) => state.name,
      // fuction 映射 this.age 为 store.state.age的值
      age: (state) => state.age,
      names(state) {
        return state.name + state.age
      }
    })
  }

当然如果对应名称相同,也可以传入数组,也可以达到上面效果

  computed: {
    ...mapState(['count', 'age', 'name']),
    ...mapState({
      names(state) {
        return state.name + state.age
      }
    })
  }

也可以为映射参数定义新名称。

...mapState({'新名字': 'xxx'})

接下来getters、mutation、actions将以此类推,如下拿actions举例!

  computed: {
    ...mapActions(['actions名']),
    ...mapActions({ 新名字: 'actions名' })
  }