2017-01-25 135 views
9

我正在学习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我有错误未捕获的ReferenceError:$路径没有定义

也许是因为我没有使用NPM现在只是Vue公司和Vuerouter的CDN版本的。任何解决方案谢谢!

更新时间: BTW在Vue公司开发的工具,我看到组件

更新在$路由实例:

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); 
      }, 
     }) 
+1

你能不能也把的那部分组件代码你在哪里获取param.id?添加代码 –

+0

。你可以检查。谢谢! –

+1

你可以尝试console.log(这个。$ route.params.id)而不是 –

回答

11

由于Sandeep Rajoria

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

+2

在添加'this'后我得到'TypeError:无法读取未定义的属性'$ route' –

+0

需要更多细节。对我来说,它的工作原理 –

+0

现在正在工作 –

1

如果您使用vue v2 & vue-router v2,则vue-cli生成样板文件以访问路由器,例如,从零部件是进口的路由器(路由器/ index.js出口)

<script> 
    import Router from '../router'; 

然后在你的代码,你可以使用路由器的功能,如:

Router.push('/contacts'); // go to contacts page 
2
import Vue from 'vue' 
import Router from 'vue-router'; 

Vue.use(Router) 

const router = ... 
+2

有些叙述很好解释你在这里做了什么。 –