【问题标题】:Vuejs simplify vuex action callVuejs 简化了 Vuex 动作调用
【发布时间】:2019-10-25 10:59:00
【问题描述】:

我正在通过如下组件调用商店操作:

sublitPost(){
    this.$store.dispatch({type:"submitPost", userPost:this.newPost});
}

商店操作如下所示:

  actions: {
    submitPost({commit, state}, userPost: any) {
     /...rest code here

尽管如此,我想简化这一点并将操作称为:

sublitPost(){
    this.$store.dispatch("submitPost", this.newPost);
}

我必须对动作签名进行哪些调整?我尝试过的操作如下:

  actions: {
        submitPost(userPost: any) {
          console.log({userPost})
         /...rest code here

但在这种情况下,接收到的对象看起来不正确。我在控制台日志中得到的是:

欢迎任何帮助

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    你应该改变你的语法:

    actions: {
        submitPost(state, data) {
          console.log(data)
        {
    

    【讨论】:

    • 我做到了,效果很好。谢谢你。这是否意味着每个动作都应该以“状态”作为第一个参数开始?
    • 不,您也可以只调用它submitPost(context) 并使用context.statecontext.commit 等更改状态或提交一些突变。使用submitPost({state, commit}, data) 您可以传递数据并提交例如一些突变
    【解决方案2】:

    我已将我的商店划分为模块,因此我正在导出我的所有突变、动作、吸气剂。 我正在使用有效负载从我的操作中提交一个突变,这里有效负载是一个具有属性 currentWidth 的对象

    export function fetchDeviceCurrentWidth ({ commit, state }, payload) {
      commit('updateDeviceCurrentWidth', payload)
    }
    
    

    我的突变

    export function updateDeviceCurrentWidth (state, payload) {
      state.currentDeviceWidth = payload.currentWidth
    }
    
    

    我的吸气剂

    export const currentDeviceWidth = state => state.currentDeviceWidth
    

    这是我发送动作的地方:

    myEventHandler () {
          this.$store.dispatch('fetchDeviceCurrentWidth', {
            currentWidth: window.innerWidth
          })
        }
    

    vuex store 的使用方法有很多,但我喜欢根据功能或组件将 store 分解为模块。

    【讨论】:

      猜你喜欢
      • 2016-12-23
      • 2021-02-18
      • 1970-01-01
      • 2019-02-02
      • 2018-08-23
      • 2018-07-12
      • 2017-07-24
      • 2022-01-27
      • 1970-01-01
      相关资源
      最近更新 更多