首页 > 解决方案 > 在 Vue SPA 站点中重新加载同一页面

问题描述

我已经尝试了十几种方法来做到这一点。.htaccess在 apache 托管(我的网站托管的首选环境)中,通过 heroku,通过带有_redirects文件和netlify.toml文件的 netlify。而且它们似乎都不起作用。Vue 推荐这样写.htaccess文件:

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
   RewriteRule ^index\.html$ - [L]
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule . /index.html [L]
</IfModule>

但它不会重新加载到同一页面。它重新加载到 index.html 主页面。现在,我明白为什么要这样做了。本质上,SPA 中的每个页面都是一个 index.html。正是这些组件使它看起来像一个不同的页面。但是,这适用于我见过的每个 SPA 网站。所以当我重新加载时,必须有一种方法让渲染保持一致。

如果它很重要,这里是一些相关的代码

环境

QUASAR.CONF.JS

  build: { vueRouterMode: "history" }

ROUTES.JS(最小)

import Layout from "layouts/Layout.vue";
import Home from "pages/Index.vue";
import About from "pages/About.vue";
import Contact from "pages/Contact.vue";


const routes = [
  {
    path: "/",
    component: Layout,
    children: [
      { path: "/", component: Home },
      { path: "/about", component: About },
      { path: "/contact", component: Contact }
    ]
  }
];

// Always leave this as last one
if (process.env.MODE !== "ssr") {
  routes.push({
    path: "*",
    component: () => import("pages/Error404.vue")
  });
}

export default routes;

如果你有什么需要看的,请告诉我。

问题页面加载正常,但是当我重新加载页面时,它会加载主页(主页),即索引页面。如果没有 htaccess 代码,它会显示找不到页面(甚至不是我自己的 404)。历史模式从 URL 中删除 # 并将其置于哈希模式也不能修复它。

任何帮助,将不胜感激

标签: javascript.htaccessvue.jsvuejs2vue-router

解决方案


通过在路由文件(我的设置中的 src/routes/index.js )中设置模式和路由器,我能够毫无问题地将我的应用程序从哈希转换为历史记录:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
import NotFound from '../components/NotFound.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home,
  },
  {
    path: '*',
    component: NotFound,
  },
];

const router = new VueRouter({
  mode: 'history',
  routes,
});

export default router;

通过设置模式并导出路由器,我能够从我的应用程序中解决 404 问题。然而,Quasar 可能正在做其他事情。希望这种方法可以适合您。


推荐阅读