Vue JS,复选框和计算属性

Ham*_*bot 3 javascript vue.js

我在使用 vue、复选框和计算属性时遇到了一些问题。

我做了一个非常小的例子来展示我的问题:https : //jsfiddle.net/El_Matella/s2u8syb3/1/

这是 HTML 代码:

<div id="general">
  Variable: 
  <input type="checkbox" v-model="variable">
  Computed:
  <input type="checkbox" v-model="computed()">
</div>
Run Code Online (Sandbox Code Playgroud)

和 Vue 代码:

new Vue({
    el: '#general',
  data: {
    variable: true
  },
  compute: {
    computed: function() {
        return true;
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

问题是,我不能让 v-model="computed" 工作,似乎 Vue 不允许这样的事情。

所以我的问题是,如何利用计算数据的好处并将其应用于复选框?

这是另一个显示相同问题的 jsfiddle,但有更多代码,我试图使用计算属性来构建“选定”产品数组变量:https : //jsfiddle.net/El_Matella/s2u8syb3/

感谢您的回答,祝您有美好的一天!

nil*_*ils 6

计算属性基本上是JavaScript 的 getter 和 setter,它们像常规属性一样使用。

您可以使用 acomputed setter来设置值(目前,您只有一个 getter)。您需要有一个dataorprops属性,您可以在其中保存模型的更改,因为 getter 和 setter 没有固有状态。

new Vue({
    el: '#general',
  data: {
    variable: true,
    cmpVariable: true,
  },
  computed: { // "computed" instead of "compute"
    cmp: {
      get: function() {
          return this.$data.cmpVariable;
      },
      set: function(val) {
          this.$data.cmpVariable = val;
      },
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

此外,您不需要用括号调用计算(因为它的行为类似于常规属性):

<div id="general">
  Variable: 
  <input type="checkbox" v-model="variable">
  Computed:
  <input type="checkbox" v-model="cmp">
</div>
Run Code Online (Sandbox Code Playgroud)