Is there a way to display a 404 error in Vue without altering the URL?

Query

I'm trying to figure out how to display a 404 error in a dynamic route using Vue.js without changing the URL. Can anyone help?

This is part of my route.js file (everything seems fine)

{

    path: '/work/:id',
    name: 'work',
    component: () => import( './views/Work.vue' )

},

{

    path: '*',
    name: 'NotFound',
    component: () => import( './views/NotFound.vue' )

}

This is part of Work.vue component where I check if the route parameter exists in my static JSON. If not, I want to open the NotFound component before entering the route.

beforeRouteEnter (to, from, next) {
    next(vm => {
        vm.item = json.find(item => item.id == vm.$route.params.id)

        if(!vm.item) {
            next({name: NotFound})
        }

    })
}

The issue at hand

When I navigate to site.com/work/non-existent-id, the "NotFound" component opens up but the URL changes from site.com/work/non-existent-id to just site.com

My expectation

The desired behavior would be for site.com/work/non-existent-id to display the "NotFound" component while keeping the URL intact as site.com/work/non-existent-id

Example scenario

https://v2.vuejs.org/v2/guide/something - returns a 404 error and remains on the same URL

Answer №1

Routers are built to perform the opposite of what you're aiming for. If you intend to showcase content on any route within your application, my suggestion would be to create a new component and possibly trigger an event to display the desired content.

Personally, I believe that re-routing might be more suitable as it allows users to navigate back using the browser's back button. However, the best approach depends on the specific use case in this situation.

Answer №2

I have successfully implemented vue router3 and it is functioning well without requiring any changes to the URL for axios requests.

beforeRouteEnter(to,from,next) {
 axios
 .get(`http://localhost:5000/api/product/${to.params.id}`)
 .then((res) => {
    next((vm) => {
      vm.product = res.data;
      next();
    });
  })
  .catch((error) => {
     
      next({ name: 'notFound', params: [to.path]});
    
    
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm looking to utilize the Blueimp File Uploader to upload just one file

I'm trying to upload only one file using Blueimp File Upload. However, whenever I select a second file after uploading the first one, the new file gets appended below the old one instead of replacing it. How can I modify the code to replace the existi ...

Reactjs throwing an Unsupported Media Type error with code 415

I am currently working on implementing a delete function to remove banner images. Here is the code snippet for my delete function: const [del, setDel] = useState([]); const DeleteBanner = async (banner) => { setDel(banner); ...

Adding Urls in a specific format using JavaScript: A Comprehensive Guide

I am looking to insert variable data in JavaScript in the given code within the URL $(document).on('change','.sort_rang',function(){ var url = "ajax_search.php"; //console.log($("#search_form").serialize()); var data = $("#sea ...

The context of 'this' remains unestablished within the SFC Vue

I am facing a problem where, while hovering over the variable during debugging inside Chrome DevTools, I receive the following output: https://i.sstatic.net/KM1EF.png When checking the DevTools console: https://i.sstatic.net/8yF50.png Does anyone have a ...

Exploring the world of JavaScript popups

I'm having an issue with implementing a JavaScript popup on my website. I've created a jsfiddle demo, which can be found here: http://jsfiddle.net/68vGZ/ Here is the code snippet: HTML <div id="header-links"> <button id="aboutinfo" ...

Rendering with Node.js Express and Mongoose after saving data

I recently started diving into Node.js Express and Mongoose while constructing a basic blog platform. My focus is on establishing routes for handling simple database tasks, but I'm feeling uncertain about managing asynchronous functions and ensuring ...

Mastering the art of adding content slot to tooltips in Buefy

I am attempting to utilize Buefy's tooltip feature with a content slot. Instead of using the label prop to define the tooltip text, I want to use HTML tags for text formatting. Upon inspecting the source code of the tooltip component on GitHub, it ap ...

Updating parts of a list using AJAX

Recently, I've encountered a challenge where I need to enable editing functionality on a table column from a database. The goal is to make the column editable when clicked and update the value when clicked out. To achieve this, I decided to utilize A ...

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

What is the best way to send global arguments to an IIFE function?

My goal is to pass local variables as global arguments to an IIFE (Module Pattern), but I'm unsure of how to do this. Below is one of my modules that requires some variables as arguments from outside the module scope: const Event = (function(flag, l ...

CSS3 Perspective Issue: Solutions for Fixing

I'm currently working on creating a card flip animation that flips in the X axis direction. Right now, the div rotates using the rotateX() method. I attempted to add the perspective property to the upper div, but it ended up distorting my div structur ...

Adding a plane to a Three.js scene

When attempting to introduce a plane into the scene, I noticed that nothing is added when checking the children's scene. var newPlane = new THREE.Mesh( new THREE.PlaneGeometry( 2000, 2000, 8, 8 ), new THREE.MeshBasicMaterial( { color: 0xffff00, opaci ...

Utilizing Chosen JS along with the clone(true,true) method for re-rendering upon appending

I am currently utilizing the Chosen JS jQuery plugin and attempting to make it re-render every time a cloned element, with all its event listeners copied over, is added to the document. Below is my code snippet: var container = jQuery(self.options.parent ...

Discovering the bound ASP.NET AJAX event handlers for a specific DOM element

I am currently working on customizing a pre-existing ASP.NET 3.5 AJAX web application, specifically SharePoint 2010. Unfortunately, I do not have the ability to modify the source code. My task involves adding a click event handler to act as the first even ...

When converting to a React Functional Component using Typescript, an error occurred: The property 'forceUpdateHandler' could not be found on the type 'MutableRefObject<Spinner | null>'

Looking to convert the App component in this CodePen into a Functional component using Typescript. Encountering an error when attempting to run it: ERROR in src/App.tsx:13:14 TS2339: Property 'forceUpdateHandler' does not exist on type 'Mu ...

Injecting a JavaScript object into an HTML string

I am facing an issue with a JavaScript variable I have, which points to a specific DOM element that I want to display somewhere else within the DOM structure. Here is how it is defined: var salesRep = $("ul.map").attr("id","1"); My goal is to pass this v ...

Angular rxjs: Wait for another Observable to emit before subscribing

My setup involves having 2 subscriptions - one is related to my ActivatedRoute, and the other is from ngrx Store. ngOnInit() { this.menuItems$ = this.store.select('menuItems'); this.menuItems$.subscribe(data => { this.menuItem ...

When incorporating an array into a span tag, only the final string is being shown by the loop

I need assistance with changing the content of a span tag every 1.5 seconds, but currently it only displays the final word in the 'list' array. Below is my JavaScript code: var list = [ "websites", "user interfaces" ]; setInterval(fun ...

Express.js Server Side Rendering - GET request for '/json/version/'

I have a running express server that pre-renders my react application. The routes file matches the HomeContainer to the base route / and all other routes match to the page not found. import HomeContainer from 'containers/home-container/home-container ...

Unveil Secret Divs with a Click

I am in search of a way to display a hidden div when I click on a specific div, similar to the expanding images feature in Google's image search results. I have made progress with my limited knowledge of javascript, as shown in this CodePen: http://co ...