当参数改变时,如何保持前一页获取的数据?(nuxt)



当我从"/about/1"到"/about/2",我想显示从"/about/1"收到的数据和"//2";在"//2">

[/about/:page]this.$route.params.page发生变化,组件也重新挂载。

包含在"/about/1"中接收的数据的数据数组;被初始化,并成为"/about/2"中的空数组。

如何保持数据从"/about/1"//2"呢?

cf。我应该用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++
}
})
}
}
})

可以同时使用两个useAsyncData

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
}

相关内容

  • 没有找到相关文章

最新更新