蔡佳峰
蔡佳峰

Reputation: 219

Inconsistent behaviour of props for Number/String in Vue.js 2.5.16

This is a long term existing issue for me, let's say I have a parent and child component.

// parent
<div>
  // passing a dynamic value
  <child :param="timestamp"/>
</div>

// Child
props: {
  param: {
    type: Number,
    required: true,
  }
},

When the param value passed into child component, it should pass the validation.

however, it shows the error

type check failed for prop "param". Expected Number, got String.

If I changed the type into String, it still showed the error but in a opposite way

type check failed for prop "param". Expected String, got Number.

Would be grateful to know how to solve this issue, thanks.

==========================================================================

Sorry for not explaining very well in first example.

So in my code base, I pass a variable to child component, the type of the value is always Number, let's say it's a timestamp, so when I pass the value, the inconsistent error appears all the time, which really confuses me.

Meanwhile, I use v-bind since I pass dynamic variable to child component.

Upvotes: 2

Views: 5793

Answers (2)

Dominic
Dominic

Reputation: 510

I had the same issue and simply solved it by passing both possibilties in the prop definition, so instead of

props: {
     myprop: Number, 
     [..]
}

I say it may be both:

props: {
    myprop: [String, Number],
    [..]
}

I realize this might not be a clean solution if the prop value has to be exactly of a certain type, but I think I just leave this here anyways.

Upvotes: 9

Michael Giovanni Pumo
Michael Giovanni Pumo

Reputation: 14774

Just have:

<child :param="12345"/>

You do not need to bind that way.

See this example: https://codesandbox.io/s/ryv49jm594

App.vue

<template>
  <div id="app">
    <HelloWorld :param="12345" />
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld
  }
};
</script>

HelloWorld.vue

<template>
  <p>{{ param }}</p>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    param: {
      type: Number,
      required: true
    }
  }
};
</script>

Upvotes: 2

Related Questions