【问题标题】:Two-way Computed Property with Vuejs class components带有 Vuejs 类组件的双向计算属性
【发布时间】:2019-11-12 20:27:02
【问题描述】:

在使用 class-style components 时,是否可以在 vuejs 中使用 双向计算 属性?在我的情况下,给定一个带有简单 vuex 商店的应用程序,有没有办法使用v-model 将商店值绑定到 select

vuex documentation中有一个双向绑定的例子:

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

但是我没有让它与类组件一起使用。我尝试了类似的东西

private get myvalue(): boolean {
  return store.state.myvalue;
}

/* Same type of function I would use when using @input one-way binding*/
private set myvalue(e: Event /* Wrong type for the setter... */) {
  const target: HTMLSelectElement = e.target as HTMLSelectElement;
  const value = target.value;

  if (Boolean(value)) {
    store.commit("myvalue", target.value);
  }
}

但这显然行不通,因为 getter/setter 总是具有相同的数据类型。 myvalue 的类型是 bool,但是将它传递给这两个函数并不能正常工作,因为当绑定到 select 时像这样

<select v-model="myvalue">
  <option value="false">No</option>
  <option value="true">Yes</option>
</select>

setter 似乎没有得到值。

我还尝试手动将值绑定到select(就像您对文本输入所做的那样),但在select 选项上使用:selected 不起作用(始终选择第一个选项)。

【问题讨论】:

  • 如果myvalue 是布尔值,那么您可能需要通过执行:value="false":value="true" 来确保选项值也是布尔值而不是字符串。
  • @DecadeMoon 我会调查的。我在测试是否选择了选项时检查了这一点,但在设置值时没有检查。感谢您的提示。

标签: javascript html vue.js data-binding


【解决方案1】:

过了一会儿我就开始工作了。毕竟只使用类 setter 和 getter 是解决方案:

<select v-model="myvalue">
  <option :value="false">No</option>
  <option :value="true">Yes</option>
</select>

private get myvalue(): boolean {
  return store.state.myvalue;
}

private set myvalue(value: boolean) {
  store.commit("myvalue", value);
}

为基本功能工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2019-03-31
    • 2017-08-23
    • 2020-02-05
    • 2018-09-27
    • 2019-06-22
    • 2019-02-11
    相关资源
    最近更新 更多