2016-11-18 100 views
1

我試圖用vue-router,以顯示不同的路線不同的組件。但它似乎沒有工作。VUE路由器不正確的路由,任何組件都顯示

我已編譯的程序here的codepen。

main.js只是定義了路由器和啓動應用VUE。它導入組件並設置路線。

import scss from './stylesheets/app.styl'; 

import Vue from 'vue'; 
import VueRouter from 'vue-router'; 
import Resource from 'vue-resource'; 

import App from './components/app.vue'; 
import Home from './components/home.vue'; 
import Key from './components/key.vue'; 
import Show from './components/show.vue'; 

// Install plugins 
Vue.use(VueRouter); 
Vue.use(Resource); 

// Set up a new router 
var router = new VueRouter({ 
    mode: 'history', 
    routes:[ 
    { path: '/home', name: 'Home', component: Home }, 
    { path: '/key', name: 'Key', component: Key }, 
    { path: '/show', name: 'Show', component: Show }, 

    // catch all redirect 
    { path: '*', redirect: '/home' } 
    ] 
}); 

// For every new route scroll to the top of the page 
router.beforeEach(function() { 
    window.scrollTo(0, 0); 
}); 

var app = new Vue({ 
    router, 
    render: (h) => h(App) 
}).$mount('#app'); 

我app.vue真的很簡單,只是一個包裝DIV和router-view

<script> 
    export default { 
    name: "app" 
    } 
</script> 

<template lang="pug"> 
    .app-container 
    router-view 
</template> 

其他三個是路由器應該顯示部件也同樣簡單,每一個看起來基本上是相同的。只是nameh1內容是不同的。

<script> 
    export default { 
    name: "home" 
    } 
</script> 

<template lang="pug"> 
    h1 Home 
</template> 

的WebPack創造一切條件爲app.js沒有任何錯誤。我有一個超級簡單的index.html文件,我在Chrome中打開。

<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Sagely Sign</title> 
    </head> 
    <body> 
    <div id="app"></div> 
    <script src="js/app.js"></script> 
    </body> 
</html> 

看着控制檯,我看不到任何錯誤。我注意到的是URL保持不變,看起來路由器沒有重定向到/home

file:///Users/username/Development/test-app/build/index.html 

我本來預計它會改變到新的路線。

file:///Users/username/Development/test-app/build/index.html#/!/home 

但即使我直接轉到該路線home.vue組件不會顯示。

回答

5

您正在使用的beforeEach方法的功能是導航後衛。導航衛兵接受3個參數:tofromnext。從Navigation Guards documentation

確保始終調用下一個函數,否則掛鉤永遠不會解決。

在這裏,您只需滾動頁面的頂部,但掛鉤永遠不會解析,因此路由器在滾動後立即停止。

寫你的函數是這樣的:

router.beforeEach(function (to, from, next) { 
    window.scrollTo(0, 0); 
    next(); 
}); 

,它應該工作。