Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default props in Vue 3 composition api are undefined (TS)

If I don't pass a value, the prop is just undefined, instead of taking the default value.

For example switchView and activeView. I have defined the props like this:

interface Props {
  config: {
    switchView?: boolean;
    activeView?: number;
    urls: {
      someUrl: string;
    };
    labels?: {
      someLabels: string;
    };
  };
}

const props = withDefaults(defineProps<Props>(), {
  config: () => ({
    switchView: true,
    activeView: 0,
    urls: {
      someUrl: '',
    },
    labels: {
      someLabel: '',
    },
  }),
});

And in the parent component, I'm passing the prop config object like so:

const config = {
  urls: {
    someUrl: '/example',
  },
  labels: {
    someLabel: 'Example label',
  },
};

And in my Vue Dev Tools I only see the passed props, but none of the default values that I've set. What am I doing wrong?

If I pass them in the config object, I get them as a prop. But I expect if I don't pass those optional values, then the defaults will take place.

like image 359
Bushima Avatar asked Dec 11 '25 11:12

Bushima


1 Answers

I found the issue. Vue has a problem with nested props, more specifically, the parent config object is the problem. By removing it it works fine.

interface Props {
  switchView?: boolean;
  activeView?: number;
  urls: {
    someUrl: string;
  };
  labels?: {
    someLabel: string;
  };
}

const props = withDefaults(defineProps<Props>(), {
  switchView: true,
  activeView: 0,
  urls: () => ({
    someUrl: '',
  }),
  labels: () => ({
    someLabel: '',
  }),
});
like image 122
Bushima Avatar answered Dec 14 '25 23:12

Bushima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!