首页 > 解决方案 > Vue复选框未随数据更改而更新

问题描述

在 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.jscheckbox

解决方案


来自官方文档

  • text 和 textarea 元素使用value属性和输入事件;
  • 复选框和单选按钮使用选中属性和更改事件;
  • 选择字段将用作道具并将更改用作事件。

推荐阅读