Vue3中如何在v-for数组项中调用方法并访问其值?
解决方法
核心问题是点击按钮时需要获取当前循环的request项,最直接且易维护的方式是在点击事件中直接传递该对象,具体实现如下:
方式一:点击事件直接传递当前request项(推荐)
在v-for循环的按钮上,将当前遍历的request作为参数传入sendApproval方法,即可在方法中直接访问该对象的属性并赋值给form。
示例代码:
<template> <table> <!-- 循环渲染pending数组中的每个request --> <tr v-for="request in pending" :key="request.id"> <td>{{ request.name }}</td> <td>{{ request.surname }}</td> <td>{{ request.email }}</td> <td> <!-- 点击时传入当前request --> <button @click="sendApproval(request)">Approve</button> </td> </tr> </table> </template> <script> import axios from 'axios' export default { data() { return { pending: [], form: { name: '', surname: '', email: '' } } }, async mounted() { // 从API获取数据并存入pending数组 const res = await axios.get('/your-api-url') this.pending = res.data }, methods: { sendApproval(request) { // 将当前request的属性赋值给form对象 this.form = { name: request.name, surname: request.surname, email: request.email } // 这里可以继续执行审批相关的逻辑,比如提交form到后端 // await axios.post('/approval-api', this.form) } } } </script>
方式二:通过DOM数据集间接获取(不推荐)
如果不想直接传递参数,也可以通过给父元素绑定data-*属性存储request数据,再通过事件对象读取,但这种方式依赖DOM结构,一旦DOM层级变化就会出错,仅作参考:
<template> <table> <tr v-for="request in pending" :key="request.id" :data-request="JSON.stringify(request)"> <td>{{ request.name }}</td> <td>{{ request.surname }}</td> <td>{{ request.email }}</td> <td> <button @click="sendApproval">Approve</button> </td> </tr> </table> </template> <script> // ...其他代码同方式一 methods: { sendApproval(e) { // 从父元素的dataset中解析出request对象 const request = JSON.parse(e.currentTarget.closest('tr').dataset.request) this.form.name = request.name this.form.surname = request.surname this.form.email = request.email } } </script>
总结:优先使用方式一,代码更直观、易维护,避免不必要的DOM操作依赖。
内容的提问来源于stack exchange,提问作者sotizerie
相关产品推荐
相关产品推荐

