2016-11-18 98 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(); 
}); 

,它应该工作。