我正在尝试使用 vue-router
为不同的路由显示不同的组件。但是它似乎不起作用。
我有一个编译程序的codepen here .
我的 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>
路由器应该显示的其他三个组件同样简单,每个看起来基本相同。只是 name
和 h1
内容不同。
<script>
export default {
name: "home"
}
</script>
<template lang="pug">
h1 Home
</template>
Webpack 将所有内容构建到 app.js
中,没有任何错误。我有一个在 Chrome 中打开的 super 简单的 index.html
文件。
<!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
组件。
最佳答案
您在 beforeEach
方法中使用的函数是一个导航守卫。 Navigation guards 接收 3 个参数:to
、from
和 next
。来自Navigation Guards documentation :
Make sure to always call the next function, otherwise the hook will never be resolved.
在这里,您只是在页面顶部滚动,但 Hook 从未解析,因此路由器在滚动后立即停在此处。
像这样写你的函数:
router.beforeEach(function (to, from, next) {
window.scrollTo(0, 0);
next();
});
它应该可以工作。
关于vue.js - vue-router 路由不正确,没有显示任何组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40683353/