【问题标题】:Vuejs Checkbox ArrayVuejs 复选框数组
【发布时间】:2022-07-15 09:33:09
【问题描述】:

我有一系列具有类似角色的菜单

d_active: 0
href: "/main-clients"
icon: null
id: 155
menu_actions: 1
menu_id: 1
name: "Clients"
parent_id: 173
roles: [{id: 1, name: "admin", guard_name: "web", created_at: "2021-10-18T08:51:20.000000Z",…},…]
0: {id: 1, name: "admin", guard_name: "web", created_at: "2021-10-18T08:51:20.000000Z",…}
1: {id: 6, name: "dev", guard_name: "web", created_at: "2021-11-15T11:16:21.000000Z",…}
sequence: 408
service_id: null
slug: "link"

我也有很多这样的动作

actions: [{id: "1", name: "Edit"}, {id: "2", name: "View"}, {id: "3", name: "Add"}, {id: "4", name: "Delete"}]
0: {id: "1", name: "Edit"}
id: "1"
name: "Edit"
1: {id: "2", name: "View"}
2: {id: "3", name: "Add"}
3: {id: "4", name: "Delete"}

然后我尝试像这样使用 v-for 循环它

<tr v-for="role in menu.roles" v-bind:key="role.id">
    <td>{{role.name}}</td>
    <td v-for="action in actions" :key="action.id">
   <input type="checkbox" :value="action.id" v-model="form.actions">
    </td>
</tr>  

问题是,每当我单击一个复选框 2 或更多时,都会被单击,这不是我想要的。我想要的是能够单击一个复选框并将其提交给负责的 API。

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    工作演示:

    new Vue({
      el: '#app',
      data: {
        actions: [{id: "1", name: "Edit"}, {id: "2", name: "View"}, {id: "3", name: "Add"}, {id: "4", name: "Delete"}],
        roles: [{id: 1, name: "admin"}]
      },
      methods: {
        check (e) {
      this.$nextTick(() => {
        if (e.target.checked) {
            console.log(e.target.value) // Pass this value in API
        }
      })
    }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <table>
      <tr v-for="role in roles" :key="role.id">
        <td v-for="action in actions" :key="action.id">
           {{action.name}} : <input type="checkbox" :value="action.id" v-model="action.checked" @change="check">
        </td>
      </tr>
      </table>
    </div>

    【讨论】:

      【解决方案2】:

      这行不通:

      v-model="form.actions"
      

      在您的 v-for 循环中,您应该使用当前迭代的 action 并将复选框绑定到布尔属性,例如action.checked.

      <td v-for="action in actions" :key="action.id">
        <input type="checkbox" :value="action.id" v-model="action.checked">
      </td>
      

      在此处阅读更多信息:https://v2.vuejs.org/v2/guide/forms.html#Checkbox

      【讨论】:

      • 收到此错误You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array because writing to the alias is like modifying a function local variable. Consider using an array of objects and use v-model on an object property instea
      • 您应该将v-model(即选中或未选中)绑定到action 的属性。我更新了我的答案。
      猜你喜欢
      • 2018-08-06
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多