【问题标题】:v-switch Returns False Value When It Checkedv-switch 在检查时返回 False 值
【发布时间】:2019-03-02 15:54:25
【问题描述】:

v-switch 有问题。我在一页上有一堆。当我检查其中任何一个时,它都会返回错误值。

<v-switch
    :name="['leave_it_' + listItem.asset_id]"
    @change="setAction(listItem)"
></v-switch>

这是我的脚本。

<script>
export default {
  data() {
    return {
      updates: {
        asset_id: [],
        leave_it: {},
        image: {},
        description: {}
      },
    };
  },
  methods: {
    setAction(listItem) {
      var action = (document.querySelector('input[name="leave_it_' + listItem.asset_id + '"]:checked') ? "Leave it Alone" : "Take an Action");
      this.$set(this.updates.leave_it, listItem.asset_id, action);
    }
  },
};
</script>

当我检查 v-switch 时,DOM 元素变为

<input aria-checked="true" role="checkbox" type="checkbox" name="leave_it_1" value="">

但是更新对象变成了这样:

updates:
  leave_it:
    1:"Take an Action"

正如您所见,即使 aria-checked 为真,对象值也等于假值。

所以,请帮助我。

【问题讨论】:

    标签: vue.js vuetify.js


    【解决方案1】:

    使用v-modelv-switch 绑定到data 值,然后使用它。

    <v-switch
        v-model='switchValue'
        :name="['leave_it_' + listItem.asset_id]"
        @change="setAction(listItem)"
    >
    </v-switch>
    
    data: {
      return {
         switchValue: false
      }
    }
    
    var action = this.switchValue ? "Leave it Alone" : "Take an Action";
    

    此外,您可能会完全失去:name。而不是@change,你可以watchswitchValue。这就是 Vue 方式

    watch:{
      theSwitch(newValue){
      }
    }
    

    这里是绑定多个复选框的示例。

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js">
      js ">
    </script>
    
    <div id="app">
      <div v-for='i of count'>
        <label>
           Item {{i}}
           <input v-model=checks[i] type='checkbox'></input>  
      </label>
      </div>
    
      <div>Values: {{checks}}</div>
    </div>
    
    
    <script>
      var app = new Vue({
        el: '#app',
        data: {
          count: 10,
          checks: Array(10).fill(false),
        },
        watch: {
          checks(value) {
            console.log('value changed', value)
          }
        }
      })
    </script>

    【讨论】:

    • 感谢史蒂文的快速回答。我忘了提到我有一堆开关。我认为由于这些多个开关,您的建议在我检查时有效,但在我取消选中时失败。我不知道为什么,但是当我添加 v-model 时它没有调用该函数。
    • 每个开关都需要一个唯一的名称,或者您可以将它们绑定到一个数组。 “它不调用函数”是什么意思?手表功能?
    • @BülentAkgül 我添加了一个 sn-p 来向您展示如何将多个元素绑定到一个数组并观察它们。您还可以使用名称作为键的映射而不是数组。
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多