Home > database >  Vue3 - script setup set default property value nested object
Vue3 - script setup set default property value nested object

Time:10-06

I'm trying to create a component that can receive a prop that is an object.

If the object is not set, I want to define a default value for it.

<script setup lang="ts">
interface LocaleText {
  text: string;
  single?: boolean;
  count?: number;
  params?: any;
}
interface Title {
  title?: LocaleText;
}
interface Filter extends Title {
  items?: string[];
}
interface Props extends Title {
  filters?: Filter[];
}
interface Data {
  selectedStatus: string;
}
const props = withDefaults(defineProps<Props>(), {
  title: (): LocaleText => ({ text: "ExampleText" }),
  filters: () => [] as Filter[],
});

function getText(text?: LocaleText): string | undefined | null {
  return text?.text ?? "null";
}
</script>
<template>
  <div>
    Example:
    {{ getText(props.title) }}
  </div>
</template>

Page is currently displaying "Example:null"

I could not figure out why this is happening.

CodePudding user response:

According to this in official docs :

As of now, the type declaration argument must be one of the following to ensure correct static analysis:

  • A type literal
  • A reference to an interface or a type literal in the same file

So the props should be a simple interface without extending another one :

<script setup lang="ts">
interface LocaleText {
  text: string;
  single?: boolean;
  count?: number;
  params?: any;
}
interface Title {
  title?: LocaleText;
}
interface Filter extends Title {
  items?: string[];
}
interface Props  {
  title:string;
  single?: boolean;
  count?: number;
  params?: any;
  filters?: Filter[];
}
interface Data {
  selectedStatus: string;
}
const props = withDefaults(defineProps<Props>(), {
  title: LocaleText => ({ text: "ExampleText" }),
  filters: () => [] as Filter[],
});

function getText(text?: LocaleText): string | undefined | null {
  return text?.text ?? "nullVal";
}
</script>
<template>
  <div>
    Example:
   {{ getText(props.title) }}
  </div>
</template>

DEMO

  • Related