【问题标题】:VueJS invert value in v-modelVueJS在v-model中反转值
【发布时间】:2020-07-15 16:47:01
【问题描述】:

这是我的代码:

<input
   v-model="comb.inactive"
   type="checkbox"
   @click="setInactive(comb.id_base_product_combination)"
>

我需要在 v-model 上应用 comb.inactive 的反转。

这是我尝试过的:

<input
    v-model="comb.inactive == 1 ? 0 : 1"
    type="checkbox"
    @click="setInactive(comb.id_base_product_combination)"
>



<input
    v-model="comb.inactive == 1 ? false : true"
    type="checkbox"
    @click="setInactive(comb.id_base_product_combination)"
>

你有其他想法吗?

【问题讨论】:

  • “你有其他想法吗?”是的,使用 Vue 计算。这不值得回答,而是更深入地了解 Vue

标签: javascript vue.js boolean v-model


【解决方案1】:

考虑使用true-valuefalse-value 作为快捷方式:

<input
    v-model="comb.inactive"
    type="checkbox"
    :true-value="false"
    :false-value="true"
>

或者在这种情况下,您可能正在寻找交替整数,您可以直接设置它们。

<input
    v-model="comb.inactive"
    type="checkbox"
    :true-value="1"
    :false-value="0"
>

【讨论】:

    【解决方案2】:

    如果您想反转 v-model,那么只需制作一个自定义输入组件!

    checkbox-inverted

    Vue.component('reverse-checkbox', {
      props: ['value', 'label'],
      template: `
        <label>
          <input
            type="checkbox"
            :checked="valueInverse"
            @input="onInputChanged"
          />
          <span>{{label}}</span>
        </label>
      `,
      computed: {
        valueInverse() {
          return !this.value;
        },
      },
      methods: {
        onInputChanged(e) {
          this.$emit('input', this.valueInverse);
        },
      },
    });
    

    用法

    然后你可以像任何其他输入组件一样将它与v-model 一起使用。 more information about custom inputs here

    <reverse-checkbox
      v-model="invertedModel"
      label="This checkbox will show the inverted value"
    ></reverse-checkbox>
    

    【讨论】:

      【解决方案3】:

      您应该执行以下操作:

      <input
         v-model="comb.inactive"
         type="checkbox"
         @click="setInactive(comb.id_base_product_combination)"
      >
      
      mounted(){
            this.comb['inactive'] = !(this.comb['inactive']);
      }
      

      为了更好的实践,你可以使用computed:

      <input
         v-model="checkedItem"
         type="checkbox"
         @click="setInactive(comb.id_base_product_combination)"
      >
      
      computed: {
            checkedItem: {
              get: function () {
                return !this.comb['inactive'];
              },
              set: function (newVal) {
                console.log("set as you want")
              }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-06-13
        • 2021-07-27
        • 1970-01-01
        • 2021-04-25
        • 2021-08-19
        • 2020-06-08
        • 2019-04-16
        • 2018-12-11
        • 2023-03-04
        相关资源
        最近更新 更多