Vue.js 中传递参数到方法的最佳实践 | 前端代码优化指南
<div class="Products">
<table>
<tr th:each="product, productStat : ${indexProducts}" th:if="${productStat.index % 3 == 0}">
<td :data-product-name="product.name" @click="getDialogData($event.target.getAttribute('data-product-name'))">
<el-image class="ProductImage" th:src="${product.imgUrl}" :fit="'cover'"></el-image>
<span class="ProductName" th:text="${product.name}">product-name</span>
</td>
<td :data-product-name="indexProducts[productStat.index + 1].name" @click="getDialogData($event.target.getAttribute('data-product-name'))">
<el-image class="ProductImage" th:src="${product.imgUrl}" :fit="cover"></el-image>
<span class="ProductName" th:text="${indexProducts[productStat.index + 1].name}">product-name</span>
</td>
<td :data-product-name="indexProducts[productStat.index + 2].name" @click="getDialogData($event.target.getAttribute('data-product-name'))">
<el-image class="ProductImage" th:src="${product.imgUrl}" :fit="cover"></el-image>
<span class="ProductName" th:text="${indexProducts[productStat.index + 2].name}">product-name</span>
</td>
</tr>
</table>
<el-button type="primary" @click="dialogVisible = true">Click</el-button>
<el-dialog title="Tips" v-model="dialogVisible">
<div class="dialog">
<div class="dialogLeft">
<el-image class="dialogImage" src="" :fit="cover"></el-image>
</div>
<div class="dialogRight"></div>
</div>
</el-dialog>
</div>
<script>
const {ref} = Vue
const products = createApp({
data() {
return {
dialogVisible: ref(false),
dialogData: ref({})
}
},
methods:{
getDialogData(name){
const _this = this
_this.dialogVisible = true
console.log('name: ' + name)
axios({
url: "http://localhost:8080/index/getProduct",
method: "get",
params: {
name: name
}
}).then(function (resp){
console.log(resp.data)
})
},
}
}).use(ElementPlus).mount(".Products")
</script>
<p>您需要使用 <code>v-bind</code> 指令将 <code>data-product-name</code> 属性绑定到 <code>td</code> 元素上,并在 <code>click</code> 事件处理程序中传递该属性的值作为参数。以下是如何修改代码:</p>
<ol>
<li>
<p><strong>使用 <code>v-bind</code> 绑定属性:</strong>
在 <code>td</code> 元素上使用 <code>:data-product-name</code> 指令将 <code>product.name</code> 属性绑定到 <code>data-product-name</code> 属性。</p>
</li>
<li>
<p><strong>传递属性值作为参数:</strong>
在 <code>click</code> 事件处理程序中,使用 <code>$event.target.getAttribute('data-product-name')</code> 获取 <code>data-product-name</code> 属性的值,并将该值传递给 <code>getDialogData</code> 方法。</p>
</li>
</ol>
<p>通过这些修改,您就可以在点击 <code>td</code> 元素时将正确的参数传递给 <code>getDialogData</code> 方法,从而实现预期功能。</p>

原文地址: http://www.cveoy.top/t/topic/qAjz 著作权归作者所有。请勿转载和采集!