Reputation: 47
When I move from "/about/1" to "/about/2", I want to show the data received from "/about/1" and "/about/2" in "/about/2"
But [/about/:page]this.$route.params.page
changes, the component is also remounted.
The data array that contained the data received in "/about/1" is initialized and becomes an empty array in "/about/2".
How do I keep the data from "/about/1" to "/about/2"?
cf.I should use async setup() & useAsyncData
<template>
<div v-for="(d, i) in showingData" :key="i">
<span>{d.title}</span>
<span>{d.description}</span>
</div>
<button @click="more">More</button>
</template>
export default defineNuxtComponent({
async setup() {
const route = useRoute()
const { data, refresh } =
await useAsyncData(() => {
return $fetch('url', {
params: {
page: route.params.page // 1 --> 2
},
method: 'get',
})
}, {
initialCache: false,
watch: [route]
})
])
return {
data,
refresh
}
},
data() {
return {
total: [], // when more button is clicked, it becomes empty...T.T
page: 1
}
},
computed: {
showingData() {
if (!this.total.length) {
this.total = this.data
} else {
this.total = this.total.concat(this.data)
}
return this.total
}
},
methods: {
// when more button is clicked, newly fetched data should be added to existing 'this.total'
more() {
this.$router.push({
params: {
page: this.page++
}
})
}
}
})
Upvotes: 1
Views: 594
Reputation: 1792
You can use two useAsyncData
at the same time.
const { data, refresh } =
await useAsyncData(() => {
return $fetch('url', {
params: {
page: route.params.page // 1 --> 2
},
method: 'get',
})
}, {
initialCache: false,
watch: [route]
})
])
// Page - 1
const { data: prevData, refresh: prevRefresh } =
await useAsyncData(() => {
return $fetch('url', {
params: {
page: route.params.page - 1
},
method: 'get',
})
}, {
initialCache: false,
watch: [route]
})
])
return {
data,
refresh,
prevData,
prevRefresh
}
Upvotes: 1