2017-05-19 137 views
2

我花了一整天試圖找出是什麼使這個例子失敗:Vue的路由器工作erraticaly

Vue.use(VueRouter); 
 

 
var PlayerDetail = { 
 
    template: '<div>FOO</div>' 
 
}; 
 
var PlayerList = { 
 
    template: '<div>BAR</div>' 
 
}; 
 

 
var routes = [{ 
 
    path: '/player', 
 
    component: PlayerList 
 
}, { 
 
    path: '/detail', 
 
    component: PlayerDetail 
 
}]; 
 

 
var appRouter = new VueRouter({ 
 
    routes 
 
}); 
 

 
var appVm = new Vue({ 
 
    appRouter 
 
}).$mount('#app');
<script src="https://unpkg.com/vue/dist/vue.js"></script> 
 
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> 
 
<div id="app"> 
 
    <h1>Hello App!</h1> 
 
    <p> 
 
    <router-link to="/player">foo</router-link> 
 
    <router-link to="/detail">bar</router-link> 
 
    </p> 
 
    <router-view></router-view> 
 
</div>

如果它正是這樣一個工程:

Vue.use(VueRouter); 
 

 
var Foo = { 
 
    template: '<div>FOO</div>' 
 
}; 
 
var Bar = { 
 
    template: '<div>BAR</div>' 
 
}; 
 

 
var routes = [{ 
 
    path: '/foo', 
 
    component: Foo 
 
}, { 
 
    path: '/bar', 
 
    component: Bar 
 
}]; 
 

 
var router = new VueRouter({ 
 
    routes 
 
}); 
 

 
var appVm = new Vue({ 
 
    router 
 
}).$mount('#app');
<script src="https://unpkg.com/vue/dist/vue.js"></script> 
 
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> 
 
<div id="app"> 
 
    <h1>Hello App!</h1> 
 
    <p> 
 
    <router-link to="/foo">foo</router-link> 
 
    <router-link to="/bar">bar</router-link> 
 
    </p> 
 
    <router-view></router-view> 
 
</div>

正如你所看到的,這兩個例子實際上都是相同的代碼,但在第一個例子中,我得到了TypeError:當路由器正在渲染時,route是未定義的。

其他人看到我在這裏失蹤的東西嗎?

回答

1

您傳遞Vue構造{ appRouter },這是簡寫形式,{ appRouter: appRouter }Vue構造函數期望擁有router屬性的對象,而不是appRouter屬性。

您需要命名你的路由器對象router準確,如果你打算把它傳遞使用對象屬性簡寫:

Vue.use(VueRouter); 
 

 
var PlayerDetail = { 
 
    template: '<div>FOO</div>' 
 
}; 
 
var PlayerList = { 
 
    template: '<div>BAR</div>' 
 
}; 
 

 
var routes = [{ 
 
    path: '/player', 
 
    component: PlayerList 
 
}, { 
 
    path: '/detail', 
 
    component: PlayerDetail 
 
}]; 
 

 
var router = new VueRouter({ 
 
    routes 
 
}); 
 

 
var appVm = new Vue({ 
 
    router 
 
}).$mount('#app');
<script src="https://unpkg.com/vue/dist/vue.js"></script> 
 
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> 
 
<div id="app"> 
 
    <h1>Hello App!</h1> 
 
    <p> 
 
    <router-link to="/player">foo</router-link> 
 
    <router-link to="/detail">bar</router-link> 
 
    </p> 
 
    <router-view></router-view> 
 
</div>

+0

非常感謝你 – panietoar

1

我想路徑和組件的組合是不正確的

var routes = [{ 
 
    path: '/player', 
 
    component: PlayerDetail 
 
}, { 
 
    path: '/detail', 
 
    component: PlayerList 
 
}];