VueJS将第一个单选按钮设置为v模型是否为空

时间:2019-07-18 09:40:07

标签: vue.js vuejs2

如果我的v模型为空,如何在v-for中检查单选按钮?

用户列表可能有所不同,所以我无法设置selectedUserId:665。我尝试使用:checked =“ index == 0”,但不适用于v模型。

	var radioVue = new Vue({
		el: "#test",
		data: {
			selectedUserId: null,
      users: [{id: 665, name: 'John'}, {id: 1135, name: 'Edward'}, {id: 7546, name: 'David'}]
		}
	});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="test">
  <div v-for="(user, index) in users">
	<input type="radio" :value="user.id" v-model="selectedUserId"> {{ user.name }}
  </div>
	<span>{{ selectedUserId}}</span>
</div>

2 个答案:

答案 0 :(得分:0)

您可以使用手表:

class AlumniImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $user = new User();
        $user->code = $row[0];
        $user->first_name = $row[1];
        $user->last_name = $row[2];
        $user->username = $row[3];
        $user->password = Hash::make($row[4]);
        $user->tel = $row[5];
        $user->email = $row[6];
        $user->gender = $row[7];
        $user->birthday = $row[8];
        $user->address = $row[9];
        $user->status_id = $row[10];
        return $user;
    }
}

答案 1 :(得分:0)

为此,您可以在v模型中对计算变量使用get / set

setter进行标准设置,而getter返回所需的用户ID,或者如果没有第一个用户的ID(如数组的第一个条目)

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>