下一个监视路由仅针对特定路径



我在我的应用程序中显示一些图像。让我们说图像显示在domain.com/wallpaper路由。我正在展示fetch()方法,并使用此代码查看查询和参数。

watch: {
"$route.query": "$fetch"
},
async fetch() {
console.log("fetched");
//My Code
},

在同一条路由上运行良好。但是当我访问主页或其他页面时,这个fetch()也会被调用一次。如何在更改到另一个路由时停止调用此方法?

这样的代码应该可以完成这项工作。

<template>
<div>
<button @click="$router.push({ name: 'wallpaper', query: { search: 'mountains' } })">
look for mountains
</button>
<button @click="$router.push({ name: 'wallpaper', query: { search: 'nuxt' } })">
look for nuxt
</button>
<button @click="$router.push({ name: 'index' })">
Go back to the homepage
</button>
</div>
</template>
<script>
export default {
watch: {
async $route(to, from) {
if (to.name !== 'wallpaper') return // if you're going to somewhere else than `wallpaper`
// the `return` will end the execution and not go further
console.log('fetch logic here in case you stay on the wallpaper route name')
await this.fetch()
},
},
}
</script>

当你改变你的查询时,你也可以再次调用fetch()方法。

对于Nuxt2,您可以使用watchQuery只监视查询更新。

https://nuxtjs.org/docs/2.x/components-glossary/pages-watchquery

例子:Fetch会在查询参数改变时立即执行,但不会在路由改变时执行:

export default {
watchQuery: ['any-query-param'],
async fetch() {
...
}
}

最新更新