分享

vue中动态给自定义属性data-xx赋值并读取内容

 hncdman 2024-04-05 发布于湖南

1、静态赋值

<img class="imgs-coat" v-for="(item,index) in coatImgs"
:key="item.coatImg" :src="item.coatImg" alt="" data-item="123" @click="chooseCoat($event,index)">

  • 1.

  • 2.

获取自定义属性

chooseCoat(e,index){
this.coatIndex = index;
console.log(e.target.dataset.item);//123
},

  • 1.

  • 2.

  • 3.

  • 4.

2、动态赋值

动态赋值和静态赋值的区别就是在data-xx前面➕:

   1)动态赋值内容为字符串

<img class="imgs-coat" v-for="(item,index) in coatImgs" :key="item.coatImg"
:src="item.coatImg" alt="" :data-item="item" @click="chooseCoat($event,index)">

  • 1.

  • 2.

获取属性同上

 2)动态赋值内容为对象

<img class="imgs-coat" v-for="(item,index) in coatImgs" :key="item.coatImg"
:src="item.coatImg" alt="" :data-item="JSON.stringify(item)" @click="chooseCoat($event,index)">

  • 1.

  • 2.

获取属性

登录后复制 

//如果不转换成字符串在转换为对象,只能显示[object,object]
chooseCoat(e,index){
this.coatIndex = index;
console.log(JSON.parse(e.target.dataset.item))
},

  • 1.

  • 2.

  • 3.

  • 4.

  • 5.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多