vue中動態給自定義屬性data-xx賦值並讀取內容


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)">

獲取自定義屬性

chooseCoat(e,index){

 this.coatIndex = index; 

console.log(e.target.dataset.item);//123 

}

2、動態賦值

動態賦值和靜態賦值的區別就是在data-xx前面➕:

   1)動態賦值內容為字符串

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

獲取屬性同上

 2)動態賦值內容為對象

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

獲取屬性

  1.  
    //如果不轉換成字符串在轉換為對象,只能顯示[object,object]
  2.  
    chooseCoat(e,index){
  3.  
    this.coatIndex = index;
  4.  
    console.log(JSON.parse(e.target.dataset.item))
  5.  
    },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM