Vue Router:URL 不加载正确的组件,而 router-link

Vue Router: URL does not load correct component while router-link does

我的项目使用 Vue2 和 Vue Router。我希望能够通过输入 URL http://example.com/stats.

来加载组件 Stats
  1. URL http://example.com/stats 不起作用,我被重定向到 / 并加载 App 组件
  2. <router-link :to="/stats">Go to stats</router-link> 完美运行

请问是Vue Router问题还是服务器配置问题。我想提一下我在 localhost 和使用 nGinx.

的服务器中都遇到过这个问题

我该如何解决这个问题?

app.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()!
    }
});

您是否已将您的网络服务器配置为 return 同一页面而不考虑 URL? 这样您的应用程序就可以加载,并且 URL 会被保留,以便路由可以接管并且 select 正确的组件一旦加载就可以了。

这个答案 为 nginx 建议以下配置:

location / {
    try_files $uri /base.html;
}

转到您的 Laravel 路线并输入:

Route::any('{all}', function () {
    return view('index'); // if your main view is "index"
})

这将确保深度链接在 Laravel 处理的所有请求上正常工作。

这是我做的

Route::get('/stats', 'HomeController@home');