Vue $route 未定义 [英] Vue $route is not defined
问题描述
我正在学习 Vue 路由器.而且我想在不使用模板文件中的
的情况下进行编程导航.我的路由器和视图:
I'm learning Vue router. And I want to made programmatic navigation without using <router-link>
in templates file.
My router and view:
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"按钮:
So by default I push to 'allVideos' route and inside that component I have a button and method for redirecting to ''editVideo' button:
<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
It works fine. But when I try to get id inside a VideoEdit component using $route.params.id
I got error Uncaught ReferenceError: $route is not defined
也许是因为我现在没有使用 npm,只是 Vue 和 Vuerouter 的 CDN 版本.任何解决方案?谢谢!
Maybe it's because I'm not using npm for now just a cdn version of Vue and Vuerouter. Any solutions? Thanks!
更新:顺便说一句,在 Vue 开发工具中我看到组件内的 $route 实例
Updated: btw in Vue dev tool I see $route instance inside the component
更新:
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);
},
})
推荐答案
我们找到了解决方案,需要在组件内部使用this.$route
,除了$route
we found solution, need to use this.$route
except $route
inside a component
这篇关于Vue $route 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!