Vue.js 如何在 v-for 循环中使用单选按钮 [英] Vue.js how to use radio buttons inside v-for loop

查看:124
本文介绍了Vue.js 如何在 v-for 循环中使用单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用单选按钮,以便用户可以选择其中一张照片作为他们的个人资料照片:

    <li><div><div><div>照片 ID:{{p.imgId}}

<input type="radio" v-model="profileImg" value="p.imgId">选择作为个人资料图片

<div><img v-bind:src="BASE_URL +'/uploads/' + userId + '/'+ p.imgId"/>

值是这样的:

created () {axios.get(this.BASE_URL + '/profile/g/myphotos/', this.jwt).then( res => {this.myPhotos = res.data.photos;this.showUploadedPhoto = true;this.profileImg = res.data.profileImg}).catch( 错误 => {控制台日志(错误);})},

选择照片后,profileImg 变量应设置为该照片的 imgId.

问题是如何让用户在这个 v-for 循环中只选择一张照片作为个人资料图片?

更新:一张我正在迭代的 myPhotos 对象的照片:

解决方案

通过提供名称,您可以将其视为一个元素

var app = new Vue({el:"#app",数据:{图像:[{imgId:1},{imgId:2},{imgId:3}],配置文件:2}})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="应用程序"><div><div v-for="图像中的图像"><input type="radio" v-model="profileImg" name="profileImg" :value="image.imgId">选择作为个人资料图片

您已选择:{{profileImg}}

I'm trying to use radio buttons, so that users can choose one of the photos as their profile photo:

<ul v-for="p in myPhotos">
  <li>
    <div>
      <div>
        <div>
          photo id: {{p.imgId}}
        </div>
        <input type="radio" v-model="profileImg" value="p.imgId"> Choose as profile image
      </div>
      <div><img v-bind:src="BASE_URL +'/uploads/' + userId + '/'+ p.imgId" /> </div>
    </div>
  </li>
</ul>

The values are otained like this:

created () {
  axios.get(this.BASE_URL + '/profile/g/myphotos/', this.jwt)
  .then( res => {
    this.myPhotos = res.data.photos;
    this.showUploadedPhoto = true;
    this.profileImg = res.data.profileImg
  })
  .catch( error => {
    console.log(error);
  })
},

When an photo is chosen, the profileImg variable should be set to that photo's imgId.

The problem is how to let users to choose only one photo as profile image inside this v-for loop?

Update: a photo my myPhotos object that I'm iterate over:

解决方案

By providing name you can treat it as one element

var app = new Vue({
  el:"#app",
  data:{
    images:[{imgId:1},{imgId:2},{imgId:3}],
    profileImg:2
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
  <div v-for="image in images">
              <input type="radio" v-model="profileImg" name="profileImg" :value="image.imgId"> Choose as profile image
  </div>
  You have selected : {{profileImg}}
 </div>
</div>

这篇关于Vue.js 如何在 v-for 循环中使用单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆