18
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Vue.js] propsでnullが入ることも想定した書き方

Last updated at Posted at 2020-08-29

propsのプロパティを一部のコンポーネントでは指定したくない時
もしくは実行するAPIなどによって値を入れたり、入れなかったりする時があるかと思います。
その場合はnullを許容するように指定します。

required: false
でプロパティの中身が必須ではないことを定義します。
default: null
でプロパティに値が入ってこない場合にデフォルトでnullを指定します。

props: {
    value: { type: String, required: false, default: null }
  }

required: falseは最悪定義しなくても警告などはでませんが、
default: nullは指定していないとコンソールで警告が出ます。

(警告はエラーのようにアプリが止まることはありませんが、予期せぬ不具合が起きる可能性があるので解消しておくようにしましょう)

Invalid prop: type check failed for prop "value". Expected String with value "null", got Null 

先ほど、

required: falseは最悪定義しなくても警告などはでません

と書きましたが、
その値が必要なものなのか、そうでないのかは、可読性を高めるためにも定義しておいた方がよいでしょう。

ちなみに
required: true
とすることで、プロパティに入ってくる値を必須とします。
この場合にもしnullなどが入ってしまうと先ほどと同じような警告が出てしまいます。

Invalid prop: type check failed for prop "value". Expected String with value "null", got Null 
18
9
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
18
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?