Vue:在自定义复选框组件中与 v-model 绑定不起作用 [英] Vue: binding with v-model in custom checkbox component doesn't work

查看:33
本文介绍了Vue:在自定义复选框组件中与 v-model 绑定不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个带有选项的自定义复选框组件,这些选项是通过 v-for 循环从具有选项和值的数组中生成的.如何将 v-model 正确绑定到复选框组件以使其正确更新?

现在的问题是模型只更新到最新选中的复选框,并没有给出包含所有选中选项的数组.

Vue.component('ui-checkbox', {道具: {标签: {类型:字符串,要求:真实,},指数: {类型:数字},输入值:{类型:字符串}},方法: {onChange(e) {this.$emit('input', e.target.value);},},模板:`

<输入:id="索引"类型=复选框":value="输入值"@change="onChange"/><label :for="index">{{ 标签 }}</div>`,})新的 Vue({el: "#app",数据: {检查选项:[{标签:'选项1',value: '选项 1 的值',},{标签:'选项2',value: '选项 2 的值',},{标签:'选项 3',value: '选项 3 的值',},{标签:'选项 4',value: '选项 4 的值',},],myCheckBoxModel:[]},})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></脚本><div id="应用程序"><span>选中的复选框:{{ myCheckBoxModel }} </span><ui-复选框v-for="(option, index) in checkOptions"v-model="myCheckBoxModel":key="索引":index="索引":input-value="option.value":label="option.label"/>

解决方案

什么时候做

this.$emit('input', e.target.value);

它就像

myCheckBoxModel = e.target.value

因此它只是将您单击的最后一个复选框的值分配给 myCheckBoxModel.如果要在myCheckBoxModel中保留所有选中的项,则需要执行以下操作:

  1. value 属性添加到ui-checkbox 组件以访问myCheckBoxModel 的当前值.Value 是此目标的默认属性名称(参见 vue 指南).
  2. 在你的 onChange 方法中将当前值复制到变量中,因为直接改变 value 属性不好
  3. 如果您的复选框被选中,则将对应的值推送到数组.如果未选中该复选框,则从数组中删除对应的值
  4. 发出 input 事件,结果数组作为值

Vue.component('ui-checkbox', {道具: {标签: {类型:字符串,要求:真实,},指数: {类型:数字},输入值:{类型:字符串},价值: {类型:数组}},方法: {onChange(e) {让 currentValue = [...this.value]如果(e.target.checked){currentValue.push(e.target.value)} 别的 {currentValue = currentValue.filter(item => item !== e.target.value)}this.$emit('input', currentValue);},},模板:`

<输入:id="索引"类型=复选框":value="输入值"@change="onChange"/><label :for="index">{{ 标签 }}</div>`,})新的 Vue({el: "#app",数据: {检查选项:[{标签:'选项1',value: '选项 1 的值',},{标签:'选项2',value: '选项 2 的值',},{标签:'选项 3',value: '选项 3 的值',},{标签:'选项 4',value: '选项 4 的值',},],myCheckBoxModel:[]}})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></脚本><div id="应用程序">选中的复选框:<span v-for="myCheckBoxModel 中的项目">{{ 物品 }};</span><ui-复选框v-for="(option, index) in checkOptions"v-model="myCheckBoxModel":key="索引":index="索引":input-value="option.value":label="option.label"/>

我不知道您是否需要以编程方式设置复选框状态,即当您更改 myCheckBoxModel 时,复选框的状态会相应更改.如果你这样做,你需要在你的 ui-checkbox 组件中观察 value 属性:设置复选框的状态取决于它的值是否在 value 数组.如果您想通过 myChexkboxModel

初始化复选框的状态,请在 created 钩子中执行相同操作

I'm trying to build a custom checkbox component with options that are generated with a v-for loop from an array with options and values. How can I bind the v-model correctly to the checkbox component so that it's correctly updated?

The problem now is that the model only updates to the latest checkbox that is checked and does not give an array with all checked options.

Vue.component('ui-checkbox', {
	 props: {   
    label: {
      type: String,
      required: true,
    },
    index: {
      type: Number
    },
    inputValue: {
      type: String
    }
  },
  methods: {
    onChange(e) {
      this.$emit('input', e.target.value);
    },
  },
	template: `<div>
    <input 
      :id="index"
      type="checkbox"
      :value="inputValue"
      @change="onChange" />
    <label :for="index">
      {{ label }}
    </label>
  </div>`,
})

new Vue({
  el: "#app",
  data: {
    checkOptions: [
      {
        label: 'Option 1',
        value: 'value of option 1',
      },
      {
        label: 'Option 2',
        value: 'value of option 2',
      },
      {
        label: 'Option 3',
        value: 'value of option 3',
      },
      {
        label: 'Option 4',
        value: 'value of option 4',
      },
    ],
    myCheckBoxModel: []
  },
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
   <span>checked Checkboxes: {{ myCheckBoxModel }} </span>
   <ui-checkbox
     v-for="(option, index) in checkOptions"
     v-model="myCheckBoxModel"
     :key="index"
     :index="index"
     :input-value="option.value"
     :label="option.label" />    
</div>

解决方案

When you do

this.$emit('input', e.target.value);

it works like

myCheckBoxModel = e.target.value

So it just assigns the value of the last checkbox you clicked to myCheckBoxModel. If you want to keep all checked items in myCheckBoxModel, you need to do the following:

  1. add value property to ui-checkbox component to have access to the current value of myCheckBoxModel. Value is default property name for this goal (see vue guide).
  2. in your onChange method copy the current value to the variable, because it's not good to mutate value property directly
  3. if your checkbox is checked, push the correspondent value to the array. If the checkbox is not checked, delete to correspondent value from the array
  4. emit input event with the resulting array as value

Vue.component('ui-checkbox', {
    	 props: {   
        label: {
          type: String,
          required: true,
        },
        index: {
          type: Number
        },
        inputValue: {
          type: String
        },
        value: {
          type: Array
        }
      },
      methods: {
        onChange(e) {
          let currentValue = [...this.value]
          if (e.target.checked) {
            currentValue.push(e.target.value) 
          } else {
            currentValue = currentValue.filter(item => item !== e.target.value)
          }
          this.$emit('input', currentValue);
        },
      },
    	template: `<div>
        <input 
          :id="index"
          type="checkbox"
          :value="inputValue"
          @change="onChange" />
        <label :for="index">
          {{ label }}
        </label>
      </div>`,
    })

    new Vue({
      el: "#app",
      data: {
        checkOptions: [
          {
            label: 'Option 1',
            value: 'value of option 1',
          },
          {
            label: 'Option 2',
            value: 'value of option 2',
          },
          {
            label: 'Option 3',
            value: 'value of option 3',
          },
          {
            label: 'Option 4',
            value: 'value of option 4',
          },
        ],
       myCheckBoxModel: []
      }
    })

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
  <div id="app">
  checked Checkboxes:
       <span v-for="item in myCheckBoxModel"> {{ item }}; </span>
       <ui-checkbox
         v-for="(option, index) in checkOptions"
         v-model="myCheckBoxModel"
         :key="index"
         :index="index"
         :input-value="option.value"
         :label="option.label" />    
  </div>

I don't know if you need to set checkbox state programmatically, i.e. when you change myCheckBoxModel the state of checkboxes changes correspondently. If you do, you need to watch value property in your ui-checkbox component: set the state of the check box in dependance of if its value is in value array. Do the same also in created hook if you want to initialize the state of checkboxes by myChexkboxModel

这篇关于Vue:在自定义复选框组件中与 v-model 绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆