我的项目使用 Vue2 和 Vue Router。我希望能够加载组件 Stats
通过输入 URL http://example.com/stats
.
- 网址
http://example.com/stats
不起作用,我被重定向到/
并加载App
组件 -
<router-link :to="/stats">Go to stats</router-link>
完美运行
请问是Vue Router的问题还是服务器配置的问题。我想提一下我在 localhost
中都遇到过这个问题。我的服务器使用 nGinx
.
我该如何解决这个问题?
应用程序.js:
const routes = [
{ path: '/', component: App },
{ path: '/stats', component: Stats },
{ path: "*", component: PageNotFound },
{ path: '/admin', meta: { requiresAdmin: true }, component: Admin},
{ path: "/not-authorized", component: NotAuthorized },
];
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes,
})
const app = new Vue({
el: '#app',
router,
data () {
return {}
},
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAdmin)) {
if (!Store.state.isAdmin) {
axios.post('/isAdmin').then((response) => {
if(response.data.isAdmin){
next();
}
else {
next({
path: '/not-authorized',
})
}
});
}
else {
next();
}
}
else {
next();
}
}
else {
next(); // make sure to always call next()!
}
});
最佳答案
您是否已将网络服务器配置为无论 URL 是什么都返回相同的页面? 这样您的应用程序就可以加载,并且 URL 会被保留,以便路由可以接管并在加载后选择正确的组件。
这个答案https://stackoverflow.com/a/7027686/7816087为 nginx 建议以下配置:
location / {
try_files $uri /base.html;
}
关于javascript - Vue 路由器 : URL does not load correct component while router-link does,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43282693/