Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot figure out how vue-router works

I have a Vue.js project with the following router:

import Vue from 'vue';
import Router from 'vue-router';
import Overview from '@/components/Overview';
import Experiment from '@/components/ForExperiment';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      redirect: 'test',
    },
    {
      path: '/overview',
      component: Overview,
    },
    {
      path: '/overview/from/:from/to/:to',
      name: 'overview',
      component: Overview,
    },
    //... some other urls goes here.
    {
      path: '/test',
      name: 'test',
      component: Experiment,
    },
  ],
});

If I open http://localhost:8080 in a browser I am redirected to http://localhost:8080/#/test. Why not just http://localhost:8080/test? Where does the '#' symbol come from?

And why if I open http://localhost:8080/test am I redirected to http://localhost:8080/test#/test?

And what is even more strange, if I open http://localhost:8080/overview I am redirected to http://localhost:8080/overview#/test, so the Overview component is not displayed.

What can cause these strange effects?

like image 419
Alexey Starinsky Avatar asked Oct 18 '25 18:10

Alexey Starinsky


2 Answers

Vue router has different modes. The default mode when a browser is detected is hash. The current route is determined by the hash part of the url. The upside of this approach is that no serverside configuration is required. All urls point at the same resource (e.g. the route), which you can make your index.html file.

You can change this mode to history. The history mode uses the history api of the browser. It will only work in recent browsers, but support should not be an issue at this point. It will also require server side configuration in that you need to internally rewrite your router urls to the same file. If you would not do that, refreshing the page will show a 404 page instead of the page you want to see.

like image 99
Sumurai8 Avatar answered Oct 20 '25 15:10

Sumurai8


vue-router default mode is hash mode, that is why you see a # on your URL. It uses the URL hash to simulate a full URL without reloading the page if it changes.

To get rid of the hash, we can use vue-router history mode. Change the mode like so:

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

This leverages the History API.

If you want to use the history mode, you'll need to change your server configuration. Vue Router docs has some examples here.

like image 44
Ricky Avatar answered Oct 20 '25 16:10

Ricky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!