1

I have user data in DB. I want to set default check radio button with user data in database. Without v-model it works fine but if i put v-model on input, "checked" is not working. Anybody has suggestions?

My code is:

<template>
 <div v-for="user in users">
  <input v-model="theUser.role" type="radio" id="admin" value="admin" :checked="user.role === 'admin'">
  <label for="admin">Admin</label><br>
  <input v-model="theUser.role" type="radio" id="user" value="user" :checked="user.role === 'user'">
  <label for="role">User</label>
 </div>
</template>

export default {
  data: () => ({
    theUser: {
      role: '',
      active: '',
    },
  }),
};
1
  • 1
    let the initial value for theUser.role='admin' or theUser.role='user' Commented Sep 11, 2020 at 21:06

1 Answer 1

2

Because you define the value for radio input is admin or user.

So you have to let theUser.role='admin' or theUser.role='user'.

For your case, one solution should be initials theUser.role by loop users then assign correct default value in life hook=created().

Like below demo:

new Vue ({
  el:'#app',
  data () {
    return {
      users: [
        {role: 'admin', name: 'a'},
        {role: 'user', name: 'b'}
      ],
      theUsers: []
    }
  },
  created () {
    this.theUsers = this.users.map((user) => {
      return {
        role: user.role
      }
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
 <div v-for="(user, index) in users" :key="index">
  <input v-model="theUsers[index].role" type="radio" id="admin" value="admin">
  <label for="admin">Admin ({{user.name}})</label><br>
  <input v-model="theUsers[index].role" type="radio" id="user" value="user">
  <label for="role">User ({{user.name}})</label>
 </div>
 <pre>{{theUsers}}</pre>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

oh i see. then no need to use checked if i use v-model. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.