「短文」如何在 Vue 中复制文本到剪贴板
November 04, 2022
1 min
由于它的列表渲染功能,Vue 使得在项目中使用表格变得非常容易。使用几行 HTML 和一个 v-for 循环,您可以为数组中的每个元素创建一个包含一行的表格。 vue要打印表格的每一行,必须将v-for放在表格的tr标签中。您将在每个 td 标记中循环的数组中添加数据元素,如下所示:
示例代码如下:
<script src="https://unpkg.com/vue@next"></script> <div id="example"> </div> <script> Vue.createApp({ template: ` <table class="table"> <thead> <tr> <th scope="col">Country</th> <th scope="col">Value</th> </tr> </thead> <tbody> <tr v-for="name in info" :key="name.Country"> <td>{{name.Country}}</td> <td>{{name.Value}}</td> </tr> </tbody> </table> `, data() { return { info: [ { Country: "United States", Value: "12394" }, { Country: "Russia", Value: "6148" }, { Country: "Germany (FRG)", Value: "1653" }, { Country: "France", Value: "2162" }, { Country: "United Kingdom", Value: "1214" }, { Country: "China", Value: "1131" }, { Country: "Spain", Value: "814" }, { Country: "Netherlands", Value: "1167" }, { Country: "Italy", Value: "660" }, { Country: "Israel", Value: "1263" } ] } } }).mount('#example'); </script>
假设您事先不知道列名。您可以使用 Object.keys() 遍历对象键并使用 v-for 创建列。
<div id="example"></div> <script> Vue.createApp({ template: ` <table class="table"> <thead> <tr> <th scope="col" v-for="column in columnNames">{{column}}</th> </tr> </thead> <tbody> <tr v-for="row in info" :key="row.Country"> <td v-for="column in columnNames">{{row[column]}}</td> </tr> </tbody> </table> `, computed: { columnNames:function() { const names =new Set(); for (const rowofthis.info) { for (const keyof Object.keys(row)) { names.add(key); } } return names; } }, data() { return { info: [ { Country: "United States", Value: "12394" }, { Country: "Russia", Value: "6148" }, { Country: "Germany (FRG)", Value: "1653" }, { Country: "France", Value: "2162" }, { Country: "United Kingdom", Value: "1214" }, { Country: "China", Value: "1131" }, { Country: "Spain", Value: "814" }, { Country: "Netherlands", Value: "1167" }, { Country: "Italy", Value: "660" }, { Country: "Israel", Value: "1263" } ] } } }).mount('#example'); </script>
注:本文属于原创文章,版权属于「前端达人」公众号及 qianduandaren.com 所有,未经授权,谢绝一切形式的转载