Bog*_*byk 29 javascript vue.js vue-router vue-component vuejs2
我正在学习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' })
}
})
Run Code Online (Sandbox Code Playgroud)
因此,默认情况下,我推送到'allVideos'路线,在该组件内部,我有一个按钮和方法,可以重定向到''editVideo'按钮:
<button class="btn btn-sm btn-warning" @click="editVideo(video)">Edit</button>
Run Code Online (Sandbox Code Playgroud)
方法:
editVideo(video) {router.push({ name: 'editVideo', params: { id: video.id } })},
Run Code Online (Sandbox Code Playgroud)
它工作正常.但是当我尝试在VideoEdit组件中获取id时,我得到$route.params.id了错误Uncaught ReferenceError:$ route未定义
也许是因为我现在不使用npm只是Vue和Vuerouter的cdn版本.有解决方案吗 谢谢!
更新:在Vue开发工具中使用btw我在组件中看到了$ 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);
},
})
Run Code Online (Sandbox Code Playgroud)
Bog*_*byk 37
我们发现解决方案,需要使用this.$route不同的$route组件内
Kis*_*ela 10
对于那些在添加后收到错误的人 this
TypeError: Cannot read property '$route' of undefined
我们需要使用常规函数而不是ES6 箭头函数
data: function() {
return {
usertype: this.$route.params.type
};
},
Run Code Online (Sandbox Code Playgroud)
这对我有用。
import Vue from 'vue'
import Router from 'vue-router';
Vue.use(Router)
const 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');
}
this.$router.push({ name: 'allVideos' });
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30312 次 |
| 最近记录: |