我正在学习Vue路由器。而且我想在模板文件中不使用 <router-link>
进行程序化导航。我的路由器和视图:
router = new VueRouter({
routes: [
{path : '/videos', name: 'allVideos', component: Videos },
{path : '/videos/:id/edit', name: 'editVideo', component: VideoEdit },
]
});
new Vue({
el: "#app",
router,
created: function(){
if(!localStorage.hasOwnProperty('auth_token')) {
window.location.replace('/account/login');
}
router.push({ name: 'allVideos' })
}
})
因此,默认情况下,我推送到“allVideos”路由,在该组件内部,我有一个按钮和重定向到“editVideo”按钮的方法:
<button class="btn btn-sm btn-warning" @click="editVideo(video)">Edit</button>
方法:
editVideo(video) {router.push({ name: 'editVideo', params: { id: video.id } })},
它工作正常。但是,当我尝试使用 $route.params.id
在 VideoEdit 组件中获取 id 时,出现错误 Uncaught ReferenceError: $route is not defined
也许是因为我现在没有使用 npm,只是 Vue 和 Vuerouter 的 cdn 版本。任何解决方案?谢谢!
更新: 顺便说一句,在 Vue 开发工具中,我在组件内看到了 $route 实例
更新:
var VideoEdit = Vue.component('VideoEdit', {
template: ` <div class="panel-heading">
<h3 class="panel-title">Edit {{vieo.name}}</h3>
</div>`,
data() {
return {
error: '',
video: {},
}
},
created: function () {
console.log($route.params.id);
},
})
原文由 Bogdan Dubyk 发布,翻译遵循 CC BY-SA 4.0 许可协议
感谢 Sandeep Rajoria
我们找到了解决方案,需要在组件内使用
this.$route
除了$route