Vue $ route未定义

JavaScript

西门Sam

2020-03-12

我正在学习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 } })},

它工作正常。但是当我尝试使用VideoEdit组件获取ID时$route.params.id出现错误Uncaught ReferenceError:未定义$ route

也许是因为我现在不使用npm只是Vdn和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);
            },
        })

第921篇《Vue $ route未定义》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Harry前端神无 2020.03.12

感谢Sandeep Rajoria

我们发现解决方案,需要使用this.$route不同的$route组件内

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android