AshJIT
AshJIT

Reputation: 71

Vue checkbox not updating with data change

Having problems with my data in Vue updating the UI, but only checkboxes seem to have this problem.

I'm trying to allow only one checkbox to be checked at one time, therefore I'm setting all the checkboxes to false upon clicking one of them. However, this works in the data but isn't rendered correctly in the checkboxes.

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 Code:

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

Only the checkbox appears to have an issue. If I change say the name, or a text value with a filtered array setting them all to a specific value they change but the checkboxes data change doesn't reflect in the UI, however the data in Vue is correct.

Upvotes: 7

Views: 10827

Answers (4)

Anatoly
Anatoly

Reputation: 22758

From Official docs

  • text and textarea elements use value property and input event;
  • checkboxes and radiobuttons use checked property and change event;
  • select fields use value as a prop and change as an event.

Upvotes: 6

Davison Joseph
Davison Joseph

Reputation: 71

Use :input-value instead of :value

Upvotes: 3

anniex
anniex

Reputation: 356

try using the key attributes to re-render the checkbox.

reference: https://michaelnthiessen.com/force-re-render/

Upvotes: 0

Andr&#233; Boonzaaijer
Andr&#233; Boonzaaijer

Reputation: 846

I can't exactly make it up from your code, but are you sure the property is_primary is available in the objects on load of the viewmodel? So for example this.selectedLandlords.push({ Name:'John', is_primary: false, ...}) should contain the is_primary field to make it reactive.

If not, you should use Vue.set(item, 'is_primary', false) to make it reactive.

Upvotes: 0

Related Questions