LoginSignup
0
0

More than 1 year has passed since last update.

Vueで、データによってcolspan rowspanをbindしたり、不要なら何も挿入させなくする。

Posted at

まぁv-bindを知っていれば、そんなの当たり前ですよねーって話ではあるんですが、検索してもうまく引っ掛けられなかったので、誰かの助けになれば・・・。

下記のようなデータがあって、urlがあるときは2つのセルを表示させるけれども、urlが空の場合はぶち抜きで表示させたい場合

test.json
[
  { "title": "ページA", "url": "https://example.com/page-a" },
  { "title": "ページB", "url": "" },
  { "title": "ページC", "url": "https://example.com/page-c" }
]

はじめはこのように書いていたんですが

ダメバターン
<table>
  <tr v-for="(row, index) in data" :key="index">
    <td :colspan="row.url ? 1 : 2">{{ row.title }}</td>
    <td v-if="row.url">{{ row.url }}</td>
  </tr>
</table>

これだと無駄に colspan="1" がtdの中に入ってイヤンな感じでした。

ダメパターンアウトプット
<table>
  <tr>
    <td colspan="1">ページA</td>
    <td>https://example.com/page-a</td>
  </tr>
  <tr>
    <td colspan="2">ページB</td>
  </tr>
  <tr>
    <td colspan="1">ページC</td>
    <td>https://example.com/page-c</td>
  </tr>
</table>

なので、v-bindを使ってキーごと渡すようにすればいい感じに、不要なところにはcolspanがないテーブルが書き出せます。

いい感じバターン
<template>
<table>
  <tr v-for="(row, index) in data" :key="index">
    <td v-bind="colspan(row.url)>{{ row.title }}</td>
    <td v-if="row.url">{{ row.url }}</td>
  </tr>
</table>
</tempate>
....
<script lang="ts">
...
colspan(url: string) {
  return row.url === "" ? { colspan:2 } : {}
}
</script>
いい感じパターンアウトプット
<table>
  <tr>
    <td>ページA</td>
    <td>https://example.com/page-a</td>
  </tr>
  <tr>
    <td colspan="2">ページB</td>
  </tr>
  <tr>
    <td>ページC</td>
    <td>https://example.com/page-c</td>
  </tr>
</table>

もしtdにcolspanもrowspanもセットする必要がある場合は、同じノリで下記にように返せばOKです。

colspanもrowspanもセットしたい
colspanRowspan() {
  return { colspan:2, rowspan: 2 }
}

まぁただのv-bindの使い方ではあるんですが・・・・。
v-bindなんてアレすぎるんでコレがおすすめです!とかあるとコメントもらえるとうれしいです!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0