vue3.0 v-for循環數據列表,點擊獲取循環列表當前項的某一項的數據,例如id

前言

本文爲vue 3.0語法,2.x語法從以下鏈接進入另一篇文章。

vue 2.x 寫法:v-for循環數據列表,點擊獲取循環列表當前項的某一項的數據,例如id

附上vue3.0文檔:組合式API中文文檔

vue 3.0 示例

在v-for循環語句上定義一個點擊事件,傳入一個參數,點擊的時候需要獲取什麼數據就傳入什麼,這裏以獲取 id 爲例。

<template>
  <div>
    <ul>
      <li
        class="item"
        v-for="(item, index) in arrData"
        :key="index"
        @click="getDataId(item.id)"
      >
        {{ item.title }}
      </li>
    </ul>
  </div>
</template>

<script>
import { reactive } from 'vue';
export default {
  setup() {
    const arrData = reactive([
      { id: 1, title: '第一條數據' },
      { id: 2, title: '第二條數據' },
      { id: 3, title: '第三條數據' },
      { id: 4, title: '第四條數據' },
      { id: 5, title: '第五條數據' }
    ]);

    function getDataId(id) {
      console.log('當前被點擊的id=' + id);
    }

    return {
      arrData,
      getDataId
    };
  }
};
</script>

<style>
.item {
  height: 30px;
  line-height: 30px;
  text-align: center;
  cursor: pointer;
}
</style>

點擊各項打印結果:
在這裏插入圖片描述

如果本篇文章對你有幫助的話,很高興能夠幫助上你。

當然,如果你覺得文章有什麼讓你覺得不合理、或者有更簡單的實現方法又或者有理解不來的地方,希望你在看到之後能夠在評論裏指出來,我會在看到之後儘快的回覆你。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章