简体   繁体   中英

Cannot pass props in component from Vue router

Hi I'm trying to pass props from my vue router but it's not printing anything and when logged in mounted it's returning undefined, but its giving value when I'm trying console.log(this.$route.params.id); when I try for this.id returns undefined or rather in my User template its not outputting anything, same code is working in the online tutorial that I'm watching, please help me, is there any modification happened in a recent release

 let User = { props: ['id'], template: ` <div>Hello # {{id}}</div> `, mounted() { console.log(this.$route.params); // this is returning the value console.log(this.id); // this is giving undefined } } let App = { template: ` <div class="wrapper"> <router-view></router-view> </div> ` } let router = new VueRouter({ routes: [{ path: '/user/:id', component: User, props: true }, ], }) let app = new Vue({ el: '#app', router: router, components: { 'app': App } }) router.push('/user/1')
 <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script src="https://unpkg.com/vue-router@2.0.0/dist/vue-router.js"></script> <div id="app"> <app></app> </div>

You are using very old version of Vue Router. Just switch to current version - 3.5.2 - and your code will work as expected....

 let User = { props: ['id'], template: ` <div>Hello # {{id}}</div> `, mounted() { console.log(this.$route.params); // this is returning the value console.log(this.id); // this is giving undefined } } let App = { template: ` <div class="wrapper"> <router-view></router-view> </div> ` } let router = new VueRouter({ routes: [{ path: '/user/:id', component: User, props: true }, ], }) let app = new Vue({ el: '#app', router: router, components: { 'app': App } }) router.push('/user/1')
 <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script src="https://unpkg.com/vue-router@3.5.2/dist/vue-router.js"></script> <div id="app"> <app></app> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM