[Vuejs]-How to use 404 page component to current url in Nuxt

0👍

Take a look at the Nuxt documentation for error pages: https://nuxtjs.org/docs/concepts/views/#error-page.

You can create a layout file called error.vue which serves as a base for all error pages in your site. From that layout you can reference the appropriate error component. For example:

<template>
    <div>
        <NuxtLink to="/">Home page</NuxtLink>
        <PageNotFound v-if="error.statusCode === 404" :message="error.message" />
    </div>
</template>

<script>
    export default {
        props: ['error'],
        layout: 'error'
    }
</script>

Vue will automatically render the content of the error page on the invalid route. You can also programmatically open the error page by calling the context.error() method. For example:

asyncData ({ params, error }) {
    return axios.get(`https://my-api/posts/${params.id}`)
    .then((res) => {
        return { title: res.data.title }
    })
    .catch((e) => {
        error({ statusCode: 404, message: 'Post not found' })
    })
}

If you’re using the error function inside the asyncData or fetch methods, then you can access it like I showed in the answer above, otherwise in any other method defined in the Vue instance you can access it via this.error()

export default {
    data: {...},
    methods: {
        validateRoute() {
            if (404) { 
                this.error({statusCode: 404, message: "Page not found"})
            }
        },

        axiosRequest() {
            try {
                const response = await axios.get('...');
                return response;
            } catch(err) {
                this.error({statusCode: 404, message: err.message });
            }
        }
    }
}

Leave a comment