'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:
- Vue.js3
- composition API
- TypeScript
- setup in script tag
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | h0p3zZ |
Solution 2 | h0p3zZ |