【问题标题】:Vue checkbox not updating with data changeVue复选框未随数据更改而更新
【发布时间】:2020-08-11 11:25:39
【问题描述】:

我的数据在 Vue 更新 UI 时出现问题,但似乎只有复选框有这个问题。

我试图一次只允许选中一个复选框,因此我在单击其中一个复选框时将所有复选框设置为 false。但是,这在数据中有效,但在复选框中未正确呈现。

HTML:

<table class="buildings-modify--table table-full table-spacing">
    <thead>
       <tr>
          <th>Name</th>
          <th>Primary</th>
          <th>Address</th>
          <th>City/Town</th>
          <th>Province</th>
          <th>Postal Code</th>
          <th>Phone</th>
          <th>Active</th>
       </tr>
     </thead>
     <tbody>
       <tr v-for="landlord in selectedLandlords" :key="landlord.id">
         <td>{{ landlord.name }}</td>
         <td>                            
           <input type="checkbox" :value="landlord.is_primary" @change.prevent="makePrimaryLandlord(landlord)">
         </td>
         <td>{{ landlord.address }}</td>
         <td>{{ landlord.city }}</td>
         <td>{{ landlord.province}}</td>
         <td>{{ landlord.postal_code}}</td>
         <td>{{ landlord.phone }}</td>
         <td>{{ landlord.is_active ? "Yes" : "No" }}</td>
       </tr>
   </tbody>

Vue 代码:

export default {
    data: function() {
        return {
            selectedLandlords: []
        }
    },
    methods: {
        makePrimaryLandlord: function(landlord) {
            this.selectedLandlords = this.selectedLandlords.map(item => {
                item.is_primary = false; return item});
            }
        }
    }
}

只有复选框似乎有问题。如果我更改名称或带有过滤数组的文本值,将它们全部设置为特定值,它们会更改,但复选框数据更改不会反映在 UI 中,但是 Vue 中的数据是正确的。

【问题讨论】:

    标签: vue.js checkbox


    【解决方案1】:

    来自Official docs

    • text 和 textarea 元素使用 value 属性和 input 事件;
    • 复选框和单选按钮使用 checked 属性和 change 事件;
    • 选择字段使用 value 作为道具,change 作为事件。

    【讨论】:

    • 也试过用checked。没有改变任何东西。
    • selectedLandlords 是一个被 Vue 循环的对象数组;每个人都是房东
    • 在检查/取消检查之前,数组的每个项目中是否存在 is_primary 属性?
    • 似乎 this.selectedLandlords = this.selectedLandlords.filter(item => { item.is_primary = false; return item}) 根本不过滤项目,只是在每个项目中转为is_primary。是故意的吗?
    • 对不起,错字。那应该是地图。是的,is_primary 在选中/取消选中之前存在于对象上。
    【解决方案2】:

    我无法完全从您的代码中弥补,但您确定属性 is_primary 在加载视图模型的对象中可用吗?因此,例如 this.selectedLandlords.push({ Name:'John', is_primary: false, ...}) 应该包含 is_primary 字段以使其具有反应性。

    如果没有,您应该使用 Vue.set(item, 'is_primary', false) 使其具有反应性。

    【讨论】:

      【解决方案3】:

      尝试使用key 属性重新渲染复选框。

      参考:https://michaelnthiessen.com/force-re-render/

      【讨论】:

        【解决方案4】:

        使用:input-value 而不是:value

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-06
          • 1970-01-01
          • 2014-01-12
          • 1970-01-01
          • 2013-03-16
          • 1970-01-01
          • 2018-06-21
          相关资源
          最近更新 更多