Vue reactive object containing array of object

Viewed 244

I have tried many different formats, but can only make this work:

// This works
<script setup lang="ts">
import { reactive } from 'vue'
import { IPixabayItem } from '../interfaces/IPixapayItem'
const imageList: IPixabayItem[] = []
const foundImages = reactive(
    {
        images: imageList
    }
)
</script>

Somehow I would like to avoid the const 'imageList' and instantiate the 'IPixabayItem[]' inside the reactive object; but cannot make this transpile.

// This dosn't work
<script setup lang="ts">
import { reactive } from 'vue'
import { IPixabayItem } from '../interfaces/IPixapayItem'
const foundImages = reactive(
    {
        images: IPixabayItem[] = []
    }
)
</script>

Help appreciated

1 Answers

You can provide an empty array as the value for images and set IPixabayItem[] as the generic parameter of reactive.

const foundImages = reactive<{images: IPixabayItem[]}>({
    images: []
})

Playground


or you could use the as keyword:

const foundImages = reactive({
    images: [] as IPixabayItem[]
})

Playground

Related