drake035
drake035

Reputation: 2897

Default value is not passed to prop

The code below should display my prop default value ("test") since it received no other value. Yet it displays nothing. Why not?

<template>
  <div>
    {{ propValue }}
  </div>
</template>

<script setup lang="ts">
  import { defineProps } from "vue"

  const props = defineProps<{
    myProp: {
      type: string
      default: "test"
    }
  }>()

  const propValue = props.myProp
</script>

Upvotes: 0

Views: 119

Answers (1)

yoduh
yoduh

Reputation: 14739

There are two reasons why.

  1. When you use props with TypeScript you lose the ability to set default values, but it can be fixed using the withDefaults macro (you also need to separately declare a Props interface). Side note: I would not use the alternative experimental "Reactivity Transform" solution noted in the docs (it's being removed soon)
export interface Props {
  myProp?: string;
}

const props = withDefaults(defineProps<Props>(), {
  myProp: 'test'
});
  1. This one isn't actually strictly necessary, but props is a reactive object, and when you assign a single property of props to a new variable, the reactivity breaks. In order to maintain reactivity and stay synced with any future changes to props, use the toRef function
const propValue = toRef(props, 'myProp');

and be sure to import it: import { defineProps, toRef } from 'vue';

Upvotes: 0

Related Questions