randomfool
randomfool

Reputation: 89

How to bind an empty array to the props in Vue.js3?

<script lang="ts" setup>   
  interface Props {
    bigArray: string[];
  }
        
  ***const props = withDefaults(defineProps<Props>(), {
    bigArray:[],
  }*** <---- Here is the error, setting props
        
  const bigArray = ref(props.BigArray);
</script>

ITsInterface.ts

BigArray?: string[] | null;

Looking for the proper way to set up an empty array as a prop in this scenario:

Upvotes: 2

Views: 2933

Answers (2)

h0p3zZ
h0p3zZ

Reputation: 719

import { withDefaults, defineProps} from "vue";

interface Props {
    bigArray?: string[]
}

const props = withDefaults(defineProps<Props>(), {
    bigArray: () => []
})

console.log(props.bigArray);

You just needed to add the () => arrow-function for it to work.

This is shown here in the vue documentation.

And if you want to make the prop optional (as it should be with a default value) use ? after the variable-name. This will ensure there are no unnecessary warnings in the console.

Upvotes: 10

h0p3zZ
h0p3zZ

Reputation: 719

As shown in the vue documentation here.

You could do it like that:

const props = defineProps({
  bigArray: {
    type: Array,
    default: []
  }
});

This defines a prop with the name bigArray and sets the default to an empty array.

Upvotes: 0

Related Questions