Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue-router this.$route.params is empty

I'm trying to get a variable called project_id from the address bar using vue-router. I've initialized a router like so:

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'

Vue.config.productionTip = false
Vue.use(VueRouter)

/* eslint-disable no-new */
const router = new VueRouter({
  routes: [
    { path: '/project/:project_id', component: App }
  ]
})

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

And tried to access this.$route.params.project_id from within my App.vue componenet:

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <div id="center_bar">
      oh: {{this.$route.params.project_id}}
    </div>
  </div>
</template>

<script>
import ProjectList from './components/ProjectList'
import ProjectAboutBox from './components/ProjectAboutBox'

export default {
  name: 'App',
  created() {
    console.dir(this.$route.params)
  },
  components: {
    ProjectList,
    ProjectAboutBox
  }
}
</script>

However, when I write this.$route.params to the console, I see that it is an empty object.

I didn't see anyone who encountered something similar, so my guess is that I'm missing something very basic, but I can't figure out exactly what it is.

In addition, if I console.dir(this.$route) I'm seeing that fullPath is "/", even though I'm accessing http://localhost:8080/project/kljkjkj/

EDIT:

I have also found that when I create a <router-link> that leads to the address I want to parse, then clicking on it make the whole thing work, just accessing it directly by typing the address in the address bar fails

like image 336
Tom Klino Avatar asked Aug 31 '25 01:08

Tom Klino


2 Answers

I come across a similar problem.

When manually enter url or refresh the browser, the $route object is not populated.

After some investigation, I found that if a lazy-loading route is matched:

For components outside 'router-view': the $route object is not being populated even in the 'mounted' hook, but is populated later in the rendering process.

For components inside 'router-view': the $route object is populated and available immediately

My fix is to use 'computed' property instead of 'data' when try to access variable inside the $route object.

Version: "vue": "^2.6.11", "vue-router": "^3.2.0"

Node: Changing the mode from 'hash' to 'history' doesn't help in my case.

like image 81
kelvin Avatar answered Sep 03 '25 23:09

kelvin


Default vue-router is hash mode. You can try visit http://localhost:8080/#/project/kljkjkj/

You can change to history mode

const router = new VueRouter({
  mode: 'history',
  routes: [{ path: "/project/:project_id", component: App }]
});

Demo: https://codesandbox.io/s/p9v3172x6j (try to change url to https://p9v3172x6j.codesandbox.io/project/1234)

like image 28
ittus Avatar answered Sep 03 '25 21:09

ittus