【发布时间】:2017-06-11 03:55:56
【问题描述】:
我正在学习 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);
},
})
【问题讨论】:
-
您能否也将组件代码的那部分放在您要获取 param.id 的位置?
-
添加了代码。你可以检查一下。谢谢!
-
你可以试试 console.log(this.$route.params.id) 代替
-
是的,它可以工作,但我认为 $route 是全局变量......无论如何,非常感谢!
标签: javascript vue.js vuejs2 vue-component vue-router