LoginSignup
42
45

More than 3 years have passed since last update.

[Vue.js/Nuxt.js] タブなどを横一列で表示する時に、長さに応じて横幅が変わるようにしたい場合はcssでがんばらなくてもできる

Posted at

概要

[Home] [Company] [Recruit]

こういうタブ一覧みたいなやつが、横一列に広がってて長さが長くなるに応じて短くするコンポーネントをつくります。

コンポーネント名はタブ一覧がTabList、タブがTabItemとかでいいと思います。(適当)

多分scssだけでもうまくやればできるんですけど、結構めんどくさそうだったので配列の長さのpropsを渡したほうが早いなと思いました

なのでスピード重視のコードです

解決法

  • タブコンポーネントにタブ一覧Arrayのlengthをわたす
  • タブコンポーネントで長さを変えたい要素に style 属性を付ける
  • style内で width: calc(100% / アイテム数) を設定してやればOK

サンプルコード

タブ一覧コンポーネント

<template>
  <div class="switching-tabs">
    <SwitchingTab 
      v-for="(item, i) in tabItems"
      :key="`switching-tabs--${i}`"
      :name="item.name"
      :link="item.link"
      :tab-items-length="tabItems.length"
      class="switching-tabs__tab"
    />
  </div>
</template>

<script>
import SwitchingTab from '~/components/Common/SwitchingTab';

export default {
  components: {
    SwitchingTab
  },
  props: {
    tabItems: {
      type: Array,
      required: true
    }
  }
};
</script>

<style lang="scss" src="./style.scss" scoped>
</style>
.switching-tabs {
  display: flex;
}

タブコンポーネント

<template>
  <a :href="link" :style="tabStyle" class="switching-tab">
    <div class="switching-tab__container">
      <label class="switching-tab__container__label">{{ name }}</label>
    </div>
  </a>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      required: true
    },
    link: {
      type: String,
      required: true
    },
    tabItemsLength: {
      type: Number,
      required: true
    }
  },
  computed: {
    tabStyle() {
      return {
        width: `calc(100% / ${this.tabItemsLength})`
      };
    }
  }
};
</script>

<style lang="scss" src="./style.scss" scoped>
</style>

.switching-tab {
  text-decoration: none;

  &__container {
    display: flex;
    justify-content: center;
    padding: 10px 0;
    border: solid 1px #000;
    border-radius: 10px;
    background-color: #fff;

    &__label {
      color: #000;
      font-size: 1.3rem;
      font-weight: 600;
    }
  }
}

おわり

こんな感じのコードを埋め込めばそれっぽいタブ一覧みたいなコンポーネントができると思います。

42
45
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
42
45