Search code examples
vuejs3vue-composition-apivue-propsvue-typescript

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.


Solution

  • 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: '',
      }),
    });