Vue $route 未定义

新手上路,请多包涵

我正在学习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 许可协议

阅读 2.5k
2 个回答

感谢 Sandeep Rajoria

我们找到了解决方案,需要在组件内使用 this.$route 除了 $route

原文由 Bogdan Dubyk 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于添加后出现错误的人 this

TypeError: Cannot read property '$route' of undefined

我们需要使用 常规函数 而不是 ES6 箭头函数

data: function() {
    return {
      usertype: this.$route.params.type
    };
  },

这对我有用。

原文由 Kishan Vaghela 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题