vuex之state、mutations、actions

Vuex

vuex在使用时需要通过new Vuex.Store获取到对应的对象,然后进行相关的配置

state

用来保存组件中的数据,如果想要修改这里的数据,需要通过mutation进行修改

const store = new Vuex.Store({
  state: {
    msg: "Hello Vuex"
  }
})

获取到对应state中的数据

在想要使用的组件中,我们可以直接通过this.$store.state.msg获取到对应的msg数据

<template>
  <div>
    {{$store.state.msg}}
  </div>
</template>

我们还可以在组件的computed中设置计算属性获取

<template>
  <div>
    {{msg}}
  </div>
</template>

<script>
export default {
  computed: {
    // 一般情况下,计算属性的名字和state中名字保持一致
    msg () {
      return this.$store.state.msg
    }
  }
}

</script>

我们还可以使用辅助函数mapState来解决代码耦合问题

<template>
  <div>
    {{msg}}

    {{otherName}}
  </div>
</template>

<script>
import {mapState} from 'vuex'

export default {
  computed: {
    ...mapState(['msg']),

    ...mapState({
      otherName: 'msg'
    })    
  }
}
</script>

mutations

mutation是用来修改state的唯一入口,mutation本质就是一个函数

const store = new Vuex.Store({
  state: {
    msg: "Hello Vuex"
  },
  
  mutations: {
    setMsg (state, payload) {
      state.msg = payload.msg
    }
  }
})

提交mutation

提交mutation需要借助$store.commit方法

<template>
  <div>
    {{msg}}

    {{otherName}}

    <button @click="setMsg({msg: '新的内容'})">点击修改msg</button>
  </div>
</template>

<script>
import {mapState} from 'vuex'

export default {
  computed: {
    ...mapState(['msg']),

    ...mapState({
      otherName: 'msg'
    })    
  },

  methods: {
    setMsg (params) {
      this.$store.commit('setMsg', params)
    }
  }
}
</script>

我们也可以使用辅助函数mapMutations来解决一些问题

<template>
  <div>
    {{msg}}
    {{otherName}}
    <button @click="setMsg({msg: '新的内容'})">点击修改msg</button>
  </div>
</template>

<script>
import {mapState, mapMutations} from 'vuex'

export default {
  computed: {
    ...mapState(['msg']),
    ...mapState({
      otherName: 'msg'
    })    
  },

  methods: {
    ...mapMutations(['setMsg'])
  }
}
</script>

actions

action一般用来请求接口中的数据,action支持异步操作,但是action中的数据想要设置给state,必须通过mutation

const store = new Vuex.Store({
  state: {
    msg: "Hello Vuex"
  },
  
  mutations: {
    setMsg (state, payload) {
      state.msg = payload.msg
    }
  },

  actions: {
    getMsg ({commit}) {
      相关请求函数().then(res => {
        // res.data就是我们的值 需要commit给mutation
        commit('setMsg', {msg: res.data})
      })
    }
  }
})

action需要被dispatch

可以直接调用$store.dispatch方法

this.$store.dispatch('getMsg')

也可以使用辅助函数

import {mapActions} from 'vuex'

export default {
  methods: {
    ...mapActions(['getMsg'])
  },

  created () {
    this.getMsg()
  }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值