LoginSignup
0
0

Nuxt3移行備忘録 linterに怒られないpropsの用意の仕方

Last updated at Posted at 2024-06-26

Nuxt3移行備忘録 linterに怒られないpropsの用意の仕方

Nuxt 2におけるpropsの取り扱い

Nuxt 2では、propsをコンポーネントに渡す際に、以下のようにして利用していました。

<template>
  <div>
    <img :src="imageSrc" :alt="name">
  </div>
</template>

<script>
export default {
  props: {
    imageSrc: {
      type: String,
      required: true,
    },
    name: {
      type: String,
      required: false,
      default: '',
    },
  },
};
</script>

このように、propsオブジェクトを明示的に宣言し、テンプレート内で使用していました。
しかし、Nuxt 3で同様の書き方をしていると、propsが未使用なのに定義されていることで、linterに怒られる可能性があります。

propsを明示的に定義する書き方(linterに怒られるかも)

propsを定義する、Nuxt2に近しい書き方です。
propsを使用しない場合、linterに怒られます。

const props = withDefaults(
  defineProps<{
    imageSrc: string;
    name: string;
  }>(),
  {
    imageSrc: 'default/path/to/image',
    name: '',
  }
);

デストラクチャリングを使用する場合

デストラクチャリングを使用して、propsの値を個別に取り出す方法です。
linterに怒られる可能性が減ります。

const { imageSrc, name } = withDefaults(
  defineProps<{
    imageSrc: string;
    name: string;
  }>(),
  {
    imageSrc: 'default/path/to/image',
    name: '',
  }
);

withDefaultsだけで済ます場合

デストラクチャリングを使用せず、withDefaultsの内容をそのまま利用する方法です。
不要な宣言をしていないので、linterに怒られません。

withDefaults(
  defineProps<{
    imageSrc: string;
    name: string;
  }>(),
  {
    imageSrc: 'default/path/to/image',
    name: '',
  }
);
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