Vue projects, as long as they are not static pages, are usually used in conjunction with the official routing manager vue-Router.

Recently, the project had a requirement to enter a route in the address bar and jump to the corresponding routing component. In the development environment, it is possible to do this, but after the project is packaged, jump through the address bar will report an error.

Because vUE displays a component that is controlled according to vue-router on the page, directly entering the route name in the address bar cannot trigger the vue-router rules. Therefore, you can only monitor the change of the address and use the callback function to dynamically modify the route inside the component.

Mode 1: History mode

The vue-Router is in hash mode by default. Changing the mode to History mode can solve this problem, but this requires back-end cooperation and changing the server configuration. This process is a little complicated, but it is also a solution.

Method 2: Hashchange event

What is hash?

The hash is the string following the # character in the URL address.

Changing it does not cause the entire page to reload, and it can be positioned where the element ID or name is the same (anchor point).

Window.location. hash You can obtain the hash. For example localhost:8080/#/abcde location.hash=”#/abcde”.

By listening to the hash status, the vue-Router dynamically changes the route, and switches the components on the page. In this way, errors or 404 will not be reported on the page.

When the hash is modified, the HashChange event is triggered (IE8 + support) :

window.addEventListener('hashchange'.function(e) {
	console.log(e.oldURL); 
	console.log(e.newURL)
},false);
Copy the code

So add this event to app.vue:

mounted(){
	window.addEventListener('hashchange'.() = >{
		var currentPath = window.location.hash.slice(1); // Get the input route
		if(this.$router.path ! == currentPath){this.$router.push(currentPath); // Dynamic jump}},false);
}
Copy the code

This can solve the problem of invalid route jump input in the address bar.