【发布时间】:2022-11-11 09:11:22
【问题描述】:
我有动态路由http://localhost:3000/sections/slug-name。如果 URL 无效,我想显示或重定向到 404 页面。尝试使用 fetch 方法做类似this 的事情。
我知道我们可以做到 <p v-if="$fetchState.error">404 Invalid Section</p>,但有没有更好的方法来显示 404 页面。
以下是我的代码供您参考
<script>
export default {
data() {
return {
posts: {},
loader: false,
}
},
head() {
return {
title: this.posts.category_name ,
}
},
methods: {
getResults(page = 1) {
if (this.$route.query.page != page) {
this.$router.push({
query: {
page: page,
},
})
}
},
loadPosts(page) {
this.loader = true
this.$axios
.$get(`category/${this.$route.params.category}?page=${page}`)
.then((response) => {
this.posts = response
this.loader = false
})
},
},
watch: {
$route(to, from) {
this.loadPosts(to.query.page)
},
},
async fetch() {
let page = this.$route.query.page ? this.$route.query.page : 1
this.posts = await this.$axios
.$get(`category/${this.$route.params.category}?page=${page}`)
.catch((e) => {
this.$router.push({ name: 'fallback-page' })
})
},
}
</script>
【问题讨论】: