Thymeleaf 与 Vue.js 数据传递:使用 v-bind 指令实现点击事件传参
Thymeleaf 与 Vue.js 数据传递:使用 v-bind 指令实现点击事件传参
为了将 Thymeleaf 获取到的数据传递给 Vue.js 应用中的方法,你可以使用 v-bind 指令将数据绑定到 HTML 元素上,然后在点击事件中访问绑定的数据。
1. 使用 v-bind 指令绑定数据
在 td 元素上使用 v-bind 将 product.name 绑定到一个自定义属性上,例如 data-product-name:
<td @click="getDialogData" v-bind:data-product-name="product.name">
2. 修改 getDialogData 方法访问绑定数据
修改 getDialogData 方法,使其能够访问绑定的数据。你可以使用 event.target.getAttribute('data-product-name') 来获取绑定的数据:
getDialogData(event){
const _this = this
_this.dialogVisible = true
const name = event.target.getAttribute('data-product-name')
console.log('name: ' + name)
axios({
url: 'http://localhost:8080/index/getProduct',
method: 'get',
params: {
name: name
}
}).then(function (resp){
console.log(resp.data)
})
},
这样,当你点击 td 元素时,getDialogData 方法就会被调用,并且可以获取到绑定的 product.name 作为参数。
示例代码
<div class="Products">
<table>
<tr th:each="product, productStat : ${indexProducts}" th:if="${productStat.index % 3 == 0}">
<td @click="getDialogData" v-bind:data-product-name="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 @click="getDialogData" v-bind:data-product-name="${indexProducts[productStat.index + 1].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 @click="getDialogData" v-bind:data-product-name="${indexProducts[productStat.index + 2].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(event){
const _this = this
_this.dialogVisible = true
const name = event.target.getAttribute('data-product-name')
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>
总结
通过使用 v-bind 指令将 Thymeleaf 获取到的数据绑定到 HTML 元素上,并在点击事件中访问绑定的数据,可以有效地实现 Thymeleaf 与 Vue.js 应用之间的交互,完成点击事件传参。
原文地址: https://www.cveoy.top/t/topic/qAk4 著作权归作者所有。请勿转载和采集!