【问题标题】:Two way binding computed property with mappers使用映射器的两种方式绑定计算属性
【发布时间】:2021-05-07 00:34:41
【问题描述】:

我在我的 Vue 2 项目中使用 vuex。

我有这个 HTML 元素,我尝试实现两种方式绑定:

<input v-model="message">


computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}

在 get 和 set 内部我想使用映射器,这样代码看起来更干净:

computed: {
  message: {
    get () {
      return ...mapState("obj", ["message"])
    },
    set (value) {
      ...mapMutations("obj/updateMessage", value)
    }
  }
}
    

但我在两行得到错误:

return ...mapState("obj", ["message"])   -   Expression expected.

...mapMutations("obj/updateMessage", value) - Declaration or statement expected.

如何在 get 和 set 中使用映射器?

更新: mapMutations 和 mapState 被导入到组件中。

【问题讨论】:

  • @kissu,它没有解决问题。我没有投反对票!
  • 什么现在不起作用?你有同样的错误吗?

标签: javascript vue.js ecmascript-6 vuex


【解决方案1】:

您需要先导入它们,就像您所做的那样
import { mapState, mapActions } from 'vuex'
导入动作,而不是突变。实际上,只有动作是异步的,并且流程应该始终是 dispatch a action > commit a mutation > state is updated

然后,将它们插入它们所属的位置

computed: {
  ...mapState('obj', ['message']),
  // other computed properties ...
}

methods: {
  ...mapActions('obj', ['updateMessage']),
  // other methods ...
}

接下来是有趣的部分

computed: {
  message: {
    get () {
      const cloneDeepMessage = cloneDeep(this.message)
      // you could make some destructuring here like >> const { id, title, description } = cloneDeepMessage
      return cloneDeepMessage // or if destructured some fields >> return { id, title, description }
    },
    set (value) {
      this.updateMessage(value)
    }
  }
}

如您所见,我建议您也使用import cloneDeep from 'lodash/cloneDeep' 来避免直接改变状态,这要归功于cloneDeep 在访问您的状态时。
这是Vuex strict mode 会给你的警告,这就是为什么我建议只在开发中启用它。

官方文档在这部分不是很明确(您需要阅读它们的各个部分并将它们混合在一起)但它基本上是一种很好的做事方式恕我直言。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-31
    • 1970-01-01
    相关资源
    最近更新 更多