LoginSignup
35
20

More than 5 years have passed since last update.

Vue.js の props の type 指定時に String と Number の両方を許容させる

Last updated at Posted at 2018-11-07

props の type を複数指定したい・・・場合

official
<script>
  ・・・
  props: {
    // 複数の型の許容
    propB: [String, Number]
  }
  ・・・
</script>

既存実装などでそもそも渡される型の指定がないけれど、どうも数値とみなされる値が渡されてるっぽい・・・というときに・・・
type に直接 StringNumber を渡すのではなく、配列に格納すると
どうも指定した型が許容されるようです。

multiple-types-props.vue
<template lang="pug">
  span {{ puroppu }}
</template>

<script>
import Vue from 'vue';
export default Vue.extend({
  props: {
    puroppu: {
      // 文字列、数字両方
      type: [String, Number],
      // 数字のみ `type: Number` と同義
      //type: [Number],
      // 文字列のみ
      //type: [String],
      default: () => 0,
    },
  },
});
</script>

墓穴掘ってる感あるのですが子コンポーネント側で :value @input を定義してあり
v-model に渡す変数の型がふらふらしているような場合には効果があるかも・・・しれません

35
20
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
35
20