Javascript Vue JS、复选框和计算属性

Javascript Vue JS、复选框和计算属性,javascript,vue.js,Javascript,Vue.js,我在使用vue、复选框和计算属性时遇到一些问题 我举了一个很小的例子来说明我的问题: 以下是HTML代码: <div id="general"> Variable: <input type="checkbox" v-model="variable"> Computed: <input type="checkbox" v-model="computed()"> </div> 问题是,我无法使v-model=“computed”工作

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

我举了一个很小的例子来说明我的问题:

以下是HTML代码:

<div id="general">
  Variable: 
  <input type="checkbox" v-model="variable">
  Computed:
  <input type="checkbox" v-model="computed()">
</div>
问题是,我无法使v-model=“computed”工作,似乎Vue不允许这样的事情

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

下面是另一个JSFIDLE,显示了相同的问题,但有更多的代码,我试图使用计算属性构建一个“selected”products数组变量:


谢谢你的回答,祝你度过愉快的一天

计算属性基本上是,它们与常规属性一样使用

您可以使用设置值(目前,您只有一个getter)。您需要有一个
data
props
属性,您可以在其中保存模型的更改,因为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;
      },
    }
  }
});
此外,您不需要调用带括号的computed属性(因为它的行为类似于常规属性):


变量:
计算:
  • 您没有拼写
    computed
    。这里

  • 我猜你想检查产品清单上的一个项目, 因此,它可以显示在所选列表中

    而且你还想从两个列表中勾选它

    因此,您不需要
    计算属性

    对于复选框,您可以通过使用
    v-model
    参考所选集合,并设置
    value
    以确定要放入集合中的内容,从而轻松更改所选集合

    在您的例子中,这就是
    product.id

    您可能希望将对象本身保存在
    selectedProducts
    列表中, 但我强烈建议你不要那样做。 在某些情况下,由于对象是可变的,它将导致意外的结果

    因此,如果它是这样写的,它将起作用

  • newvue({
    el:'一般',
    数据:{
    产品:[{
    身份证号码:1
    }, {
    身份证号码:2
    }],
    选定产品:[]
    }
    })
    
    你好
    产品
    
    • {{product.id}
    精选产品
    • {{p}

    我尝试了这一点,但是取消选中复选框时,
    set()
    永远不会触发。
    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;
          },
        }
      }
    });
    
    <div id="general">
      Variable: 
      <input type="checkbox" v-model="variable">
      Computed:
      <input type="checkbox" v-model="cmp">
    </div>