Recently diving into the world of Vue, I've been eager to master the art of utilizing Vue router. Smooth sailing with normal routing, I decided to spice things up by experimenting with dynamic routing. To my surprise, everything ran smoothly until I attempted to pass props to these dynamic routes – causing my code to spiral into chaos.
My go-to versions for Vue and Vue router are the ones recommended by their official websites: - https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js - https://unpkg.com/[email protected]/dist/vue-router.js
The HTML structure:
<div id="app">
<h1>{{ message }}</h1>
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-link to="/user/John">Name</router-link>
</nav>
<!-- route outlet -->
<!-- component matched by route will render here -->
<router-view></router-view>
</div>
The JavaScript part:
// Route components
const Home = { template: '<div>Home</div>' };
const About = { template: '<div>About</div>' };
const User = { props: ['name'], template: `
<div>
<div>User {{ name }}</div>
<button @click="checkName">Check</button>
</div>`,
methods: {
checkName: function() {
console.log('Params name: ' + this.$route.params.name);
console.log('Props name: ' + this.name);
}
}
};
// Routes for router
const routes = [
{ path: '/', component: Home },
{ path: '/home', redirect: Home },
{ path: '/about', component: About },
{ path: '/user/:name', component: User, props: true }
];
const router = new VueRouter({
routes: routes
});
const app = new Vue({
el: '#app',
data: {
message: 'VueJS Router'
},
router: router
});
Upon navigating to the 'Name' page, the static text displays just fine while the dynamic text falls short. I inserted a button that logs the value of the name from both props and $route.params for the user's clarity. Surprisingly, clicking the button reveals an undefined value for the name in props but the correct one for the name from params. What could be causing this discrepancy?