0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VuetifyのTableで列の横幅を固定にする方法

Posted at

はじめに

VuetifyのTableで列の横幅を全て固定とする方法を調べたので、記事にします。
使用しているコンポーネントはv-data-table-serverですが、他のテーブルコンポーネントでも使えるかもしれないです。

サンプルコード

ポイント

テーブル全体の横幅はstyleで指定しないといけない

v-data-table-serverのpropsには、widthというpropsがあったのですが、指定しても機能せずでした。
したがって、styleを使って指定が必要です。

<v-data-table-server
  :style="width: 600px"

変数を使う場合は以下のように書きます。

<template>
  <v-data-table-server
    :style="{ width: tableWidth }"
  />
</template>
<script setup>
  import { ref, watch } from 'vue'

  const tableWidth = ref('');
</script>

ヘッダ全てに横幅を指定すると無視される

最初に、テーブル全体の横幅はstyleで指定しないといけないという話をしたのは、このポイントを回避するためで、
テーブル全体の横幅を設定せず、ヘッダ全てに横幅を設定すると、設定したヘッダの横幅が無視されます。

image.png

// 長くなるので省略してます
const headers = ref([
    {
      title: 'Dessert (100g serving)',
      align: 'start',
      sortable: false,
      key: 'name',
      width: '100px',
    },
    {
      title: 'Calories',
      key: 'calories',
      align: 'end',
      width: '100px',
    },
    ...
  ])

下記のように、一つでも横幅を設定しないヘッダがあると、他のヘッダは設定した横幅に従います。

// 長くなるので省略してます
const headers = ref([
    {
      title: 'Dessert (100g serving)',
      align: 'start',
      sortable: false,
      key: 'name',
      width: '100px',
    },
    {
      title: 'Calories',
      key: 'calories',
      align: 'end',
      width: '100px',
    },
    ...
    // Ironは横幅を指定しない
    {
      title: 'Iron (%)',
      key: 'iron',
      align: 'end',
    },
  ])

image.png

回避方法

この章の冒頭でも書きましたが、回避するにはテーブルの横幅を設定してあげると回避できます

v-data-table-serverに下記を追加する

<v-data-table-server
+  :style="width: 600px"

image.png

小ネタ

JSやVueに不慣れなので、詰まったポイントを備忘録として記載します

styleの指定方法

styleを渡すときに変数を使いたい場合は下記のようにしないといけない

:style="{ width: tableWidth }"

Booleanを渡す方法

BooleanをPropsで渡す場合は、:をつける必要がある
:isFlag="false"

ChatGPTの回答

false を渡す場合は、必ず v-bind (省略形 :) を使う必要があります。
単に isFlag="false" と書くと、文字列の "false" が渡されてしまい、JavaScript では文字列 "false" は truthy (真と評価される値) とみなされるため、意図通りに動作しません

styleタグ内でJSを使う

<script setup>
const props = defineProps({
  isFlag: {
    type: Boolean,
    required: false,
    default: true,
  },
})
</script>
<template>
</template>
<style>
// ここでJSを使いたい場合はv-bindを使う
body {
  width: v-bind('props.isFlag ? "100px" : "200px"');
}
</style>

文字列 → 数値の変換

JSでは文字列をいい感じに変換してくれる

const width = "100px";
const num = parseInt(width, 10)
console.log(num); // 100
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?