javascript - Vue 路由器 : URL does not load correct component while router-link does

标签 javascript vue.js vuejs2 vue-router

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

  1. 网址 http://example.com/stats不起作用,我被重定向到 /并加载 App组件
  2. <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/

相关文章:

javascript - 如何将值添加到数组中的重复键中

javascript - 使用 jquery 动态添加时 select2 不起作用

vue.js - vue树形导航(插件)如何映射路线

vue.js - 带有 jest + vuejs + vuetify 的意外标识符

javascript - 语法错误 : let is a reserved identifier on firefox

javascript - Dc.js 与行图上的 Bootstrap 样式冲突

Vue.js 两种不同的主要布局

javascript - 我可以将值传递给同级组件而不将其保存为变量吗?

javascript - onclick vue js中的多个元素

javascript - VueJs 2.0 将事件从孙子发送到他的祖父组件