【问题标题】:Table data rendering表格数据渲染
【发布时间】:2021-07-18 22:47:25
【问题描述】:

当我按下保存按钮以使用 vue 存储在变量中时,我想获取 'th' 和 'td' 的标题

我的 HTML 代码

                        <tr>
                            <th>Himalayan Salajit (Pakistan Only)*</th>
                            <td>PKR 800</td>
                            <td class="text-center">
                                <select class="form-control form-control-inline">
                                    <option>0</option>
                                    <option>1</option>
                                    <option>2</option>
                                    <option>3</option>
                                    <option>4</option>
                                    <option>5</option>
                                    <option>6</option>
                                    <option>7</option>
                                    <option>8</option>
                                    <option>9</option>
                                    <option>10</option>
                                </select>
                            </td>
                            <td class="text-right">PKR 0.00</td>
                        </tr>

【问题讨论】:

标签: vue.js


【解决方案1】:

使用数组代替所有数据和行,然后您可以使用 v-model 来捕获选择。

样本数据:

  data: [
    {
      label: "Himalayan Salajit (Pakistan Only)*",
      amount: 800,
      options: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      selectedOption: null,
    },
    {
      label: "Something",
      amount: 200,
      options: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      selectedOption: null,
    },
    {
      label: "Something Else",
      amount: 100,
      options: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      selectedOption: null,
    },
  ]

然后您可以使用这些数据并将其循环到您的模板中。由于您只需要标签和选定的选项,您可以过滤掉您不想要的其他值(示例在下面的代码和框中)。

所以你的模板现在看起来像:

<table>
  <tr v-for="(dat, i) in data" :key="i">
    <th>{{ dat.label }}</th>
    <td>{{ dat.amount }}</td>
    <td class="text-center">
      <select v-model="dat.selectedOption">
        <option v-for="(opt, i) in dat.options" :key="i">{{ opt }}</option>
      </select>
    </td>
    <td class="text-right">PKR 0.00</td>
  </tr>
</table>

我们循环遍历数组并显示我们想要的数据。

DEMO供参考

【讨论】: