You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue实现表格点击书籍ID按钮展示对应书名的方法

Vue实现点击BOOK ID显示对应书籍名的修正方案

原代码现存问题

  • 标签拼写错误:按钮标签误写为buitton,按钮原生属性type误写为typeof,且按钮未包裹在<td>标签内,会导致表格渲染错乱
  • v-for绑定key无效:循环时绑定的title字段不存在,会触发Vue渲染警告
  • 响应式变量缺失:代码中使用了errored、loading字段但未在data中声明
  • 多请求写法不规范:mounted中两个axios请求用逗号分隔,可读性差易出bug

实现逻辑

  1. 在data中新增activeBookId字段,用于记录当前点击要展示名称的书籍ID
  2. 新增匹配方法,根据传入的书籍ID从已获取的books列表中返回对应书籍名称
  3. 给按钮绑定点击事件,点击时将当前行的ID_BOOK赋值给activeBookId
  4. 在按钮旁增加条件渲染,当当前行书籍ID和activeBookId一致时,展示匹配到的书籍名
  5. 修复所有原代码的语法错误

修正后完整代码

<template>
<div>
  <table class="table table-striped">
     <thead>
        <tr>
           <th>User</th>
           <th>Book</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="booking in bookings" :key="booking.ID">
          <td>{{booking.ID_USER}}</td>
          <td>
            <button type="button" class="btn btn-light mr-1" @click="activeBookId = booking.ID_BOOK">
              {{booking.ID_BOOK}}
            </button>
            <span v-if="activeBookId === booking.ID_BOOK" class="ml-2">
              对应书籍:{{ getBookNameById(booking.ID_BOOK) }}
            </span>
          </td>        
        </tr>
      </tbody>
    </table>
 </div>
</template>
<script>
import axios from "axios" 
export default {
  name: "Prenotazioni",
  data() {
    return {
      bookings: [],
      books: [],
      activeBookId: null,
      errored: false,
      loading: true
    }
  },
  methods: {
    getBookNameById(bookId) {
      const targetBook = this.books.find(book => book.ID === bookId)
      return targetBook ? targetBook.NAME : '未找到对应书籍'
    }
  },
  mounted() {
    // 获取预约记录
    axios
      .post("https://localhost:7285/Prenotazioni/GetPrenotazione")
      .then(response => {
         this.bookings = response.data.pre
      })
      .catch(error => {
         console.log(error)
         this.errored = true
      })
      .finally(() => this.loading = false)
    // 获取书籍列表
    axios
      .post("https://localhost:7285/Libri/GetLibri")
      .then(response => {
         this.books=response.data.libro
      })
      .catch(error => {
         console.log(error)
         this.errored = true
      })
      .finally(() => this.loading = false)
  }
}
</script>

效果说明

  • 默认状态下表格仅展示每一条预约记录对应的BOOK ID
  • 点击某一行的BOOK ID按钮后,按钮右侧会立即显示该ID对应的书籍名称,点击其他行按钮会自动切换展示对应书名
  • 如果需要实现点击同个按钮切换显示/隐藏书名,只需要把点击事件改成@click="activeBookId = activeBookId === booking.ID_BOOK ? null : booking.ID_BOOK"即可

内容的提问来源于stack exchange,提问作者Mars95

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 11:45:31