首页 文章

如何将复选框值绑定到VueJS中的空对象?

提问于
浏览
0

我正在尝试将所有选中的复选框项存储在属性中 .

这是我的一个对象模型中的“通用”属性,它包含所有不同类型的数据 .

此属性初始化为null,因此Vue不理解它应该是一个数组 . 因此它只会将一个复选框值绑定到此属性 .

当我使用[]初始化此属性以将其声明为数组时,它按预期工作 . 但是,对象作为JSON在外部传递,因此将它们初始化为数组不是一种选择 .

var working = new Vue({
    el: "#a",
    data: {
        options: ["Apple", "Banana", "Citrus"],
        answers: [], //<- I'm unable to do this in my scenario
    }
});

var notWorking = new Vue({
    el: "#b",
    data: {
        options: ["Apple", "Banana", "Citrus"],
        answers: null 
    }
});

这是一个快速的JSfiddle,我展示了我的意思 .

https://jsfiddle.net/ojvfy39p/12/

我必须对“非工作示例”进行哪些调整才能实现“工作示例”的功能?一世'

1 回答

  • 1

    您可以使用事件来触发方法,而不是 v-model .

    var working = new Vue({
        el: "#a",
        data: {
        	options: ["Apple", "Banana", "Citrus"],
        	answers: [], //<- I'm unable to do this in my scenario
        }
    });
    
    var notWorking = new Vue({
        el: "#b",
        data: {
        	options: ["Apple", "Banana", "Citrus"],
        	answers: null 
        },
        methods: {
        	updateAnswers(val) {
            if(this.answers === null) {
              this.answers = [val];
            } else if(this.answers.indexOf(val) > -1) {
              this.answers.splice(this.answers.indexOf(val), 1);
            } else {
              this.answers = [...this.answers, val];
            }
          },
        }
    });
    
    console.clear();
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
    
    Working example. "Answers" initialized as array.
    <form id="a">
    <div v-for="(option,i) in options">
      <input type="checkbox" :value="option" name="option" v-model="answers"/> {{ option }}
    </div>
      <br>
      Selected items: {{ answers }}
    </form>
    <br>
    
    Not working example, "Answers" initialized as null
    <form id="b">
    <div v-for="option in options">
      <input type="checkbox" :value="option" name="option" @click="updateAnswers(option)" /> {{ option }}
    </div>
      <br>
      Selected items: {{ answers }}
    </form>
    

相关问题