[Vuejs]-VueJS set first radiobutton as checked if v-model is empty

0๐Ÿ‘

โœ…

You can use watch for that:

watch: {
  selectedUserId: {
    handler(newVal) {
      if (newVal === null || newVal === undefined) {
        this.selectedUserId = this.users[0].id
      }
    },
    immediate: true
  }
}

0๐Ÿ‘

for this you can use get/set on computed variable with your v-model

the setter does a standard set while the getter return the wanted users id or if there is not the id of the first user (as in first entry of the array)

var radioVue = new Vue({
  el: "#test",
  data: {
    selectedUserId: 7546,
    users: [{id: 665, name: 'John'}, {id: 1135, name: 'Edward'}, {id: 7546, name: 'David'}]
  },
  computed: {
    checkedUserId: {
      get() {
        // need to use == instead of === because v-model seems to set as string :/
        return this.users.some(user => user.id == this.selectedUserId) ? this.users.filter(user => user.id == this.selectedUserId)[0].id : this.users[0].id
      },
      set(val) {
        // doing a parseInt() here would allow you to use === in get
        this.selectedUserId = val
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="test">
  <div v-for="user in users">
    <input type="radio" :value="user.id" name="name" v-model="checkedUserId"> {{ user.name }} - {{ user.id }}
  </div>
  <span>{{ selectedUserId}}</span>
  <input type="text" v-model="selectedUserId">
</div>

Leave a comment