多个复选框和计算属性

多个复选框和计算属性

本文介绍了vuejs v-model,多个复选框和计算属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在单个文件组件中使用多个复选框.我需要计算属性,但我的 setter 中有布尔值 newVal 而不是数组.这是我的代码:

var demo = new Vue({el: '#demo',数据: {_checkedNames: []},计算:{已检查名称:{得到:函数(){返回 this._checkedNames;},设置:函数(新值){控制台日志(新值);//计算后我们有真/假值而不是数组this._checkedNames = newVal;}}}})
<script src="https://unpkg.com/[email protected]/dist/vue.js"><;/脚本><div id="演示"><input type="checkbox" id="jack" value="Jack" v-model="checkedNames"><label for="jack">Jack</label><input type="checkbox" id="john" value="John" v-model="checkedNames"><label for="john">John</label><input type="checkbox" id="mike" value="Mike" v-model="checkedNames"><label for="mike">Mike</label><br><span>选中的名称:{{ checkedNames }}</span>

因此,您将在控制台中看到布尔值.

更新1.详细案例说明

我正在使用模型的遗留代码,该代码作为参数传递给 vue 组件.我需要将组件标记绑定到模型的属性(上面代码中的 _checkedNames 模拟了这个模型属性).此属性通过 getter/setter(有时只是 getter)声明.我想在 v-model 构造中使用这样的属性.这个案例对我不起作用.我猜 vuejs 无法正确包装它.我正在寻找一种解决方案(或变通方法),以考虑到上述限制.

vue 论坛上有同样的问题:https://forum.vuejs.org/t/v-model-multiple-checkbox-and-computed-property/6544

解决方案

来自官方文档.

I am trying to use multiple checkboxes in single file component. And I need to computed property, but I have boolean newVal instead of array in my setter. Here is my code:

var demo = new Vue({
    el: '#demo',
    data: {
        _checkedNames: []
    },
    computed: {
      checkedNames: {
        get: function () {
          return this._checkedNames;
        },
        set: function (newVal) {
          console.log(newVal); //with computed we have true/false value instead of array
          this._checkedNames = newVal;
        }
      }
    }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="demo">
  <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
  <label for="jack">Jack</label>
  <input type="checkbox" id="john" value="John" v-model="checkedNames">
  <label for="john">John</label>
  <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
  <label for="mike">Mike</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
</div>

So, you will see boolean value in the console.

Update 1. Detail case explanation

I'm using legacy code of the model, which is being passed as a parameter to vue component. And I need to bind component markup to the model's property (_checkedNames in code above simulates this model property). This property declared via getter/setter (sometimes just getter). And I want to use such a property in v-model construction. This case doesn't work for me. I guess vuejs can't wrap it correctly. And I'm loking for a solution (or a workaround) that will take in account mentioned restrictions.

Here is the same question in vue forum: https://forum.vuejs.org/t/v-model-multiple-checkbox-and-computed-property/6544

解决方案

From the official documentation.

这篇关于vuejs v-model,多个复选框和计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:32