Refreshing the current page within a Vue single-page application website

I've attempted numerous methods to resolve this issue. I have tried using .htaccess in an Apache hosting environment (which is my preferred setup for hosting my site), Heroku, and Netlify with both a _redirects file and netlify.toml file. Unfortunately, none of these approaches have been successful. Vue suggests creating the .htaccess file like this:

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

However, the issue persists where it reloads to the main index.html page instead of staying on the same page when reloaded. While I understand why this happens, as every page in a Single Page Application is essentially an index.html file, there should be a way to ensure consistent rendering when reloading.

In case it's relevant, here are some related details:

ENVIRONMENT

  • VueJS 2
  • Quasar 1.0
  • Firebase
  • Vue Router (included by default in VueJS)

QUASAR.CONF.JS

  build: { vueRouterMode: "history" }

ROUTES.JS (basic structure)

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;

If you require any additional information or code snippets, please let me know.

PROBLEM The initial page loads correctly, but upon reloading a page, it defaults back to the main index page (HOME). Even without the htaccess code, it displays a "Page not found" error rather than my custom 404 page. History mode eliminates the # from the URL, and switching to Hash mode does not solve the issue either.

Any assistance or insights on resolving this matter would be greatly appreciated.

Answer №1

I successfully transitioned my app from hashes to history without any issues by configuring the mode and router in the routes file (src/routes/index.js within my setup):

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;

By ensuring the correct mode setting and exporting of the router, I successfully resolved the 404 error in my application. It is possible that Quasar may be employing a different strategy behind the scenes. Hopefully, this method can assist you with your own implementation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

Storing past entries in a local storage using JavaScript

Currently, I am developing a JavaScript program that involves 3 input boxes. The program is designed to display whatever is typed into each input box on the page. To store and re-display previous submissions, I have implemented local storage. However, I en ...

Accessing a frame inside an iframe using jQuery once the frame has fully loaded

Looking to access an element within a frame using jQuery. Here is the structure: <iframe id="frame1"> <frameset id="frameset"> <frame id="frame2"> <div id="exampleDiv">text</div> </frame> </frameset> < ...

In the realm of Vue, the proper way of writing is to follow the first method, while the second approach is considered incorrect. But why is that the case

{{str.split('').reverse().join()}} {{arr.reverse().join()}} An issue arises when attempting to execute the second line of code. There is a possibility of encountering an infinite update loop within a component render function. ...

Displaying only the final item from an array when clicking in an ng-repeat loop

My objective is to display the details of each value from my data in a pop-up window. However, instead of showing three different values, the pop-up only displays the last value from an array three times. This is the HTML code I am using: <div ng-re ...

leveraging an array from a separate JavaScript file within a Next.js page

I am facing a situation where I need to utilize an array from another page within my Next.js project. However, it seems that the information in the array takes time to load, resulting in encountering undefined initially when trying to access it for title a ...

Manipulating the DOM using Vue.js and jQuery can significantly improve the

I'm seeking advice on how to handle a situation where I need direct access to DOM elements while using VUE.JS. Currently, I am using the Fomantic-UI framework (a fork of Semantic UI) and it takes around 100ms (?) for an element to be created, making i ...

Error: Attempting to access the properties `line_items.amount`, `line_items.currency`, `line_items.name`, `line_items.description`, or `line_items` is not allowed

Hi there, I'm currently working on creating an Amazon-inspired platform and I've encountered an error while trying to integrate Stripe with the project. Can anyone provide some assistance? You can refer to the video tutorial I'm using by fol ...

How come the styles in my CSS file aren't being applied to my images based on their class or ID?

When I apply a className or id to my img tag in my JavaScript (using React.js) and then add a style that references that id or class, the style does not get applied. However, when I do the same for a div, everything works perfectly fine. <--JavaScript- ...

Acquire a JSON response from a web address by utilizing JavaScript

If you navigate to , you will find a JSON file filled with information about your current geolocation. My goal is to save this JSON data into JavaScript variables, allowing me to manipulate and extract specific fields from the file. ...

Ensuring the value of a v-text-field in Vuetify using Cypress

I am currently developing an end-to-end test suite using Cypress for my Vue and Vuetify frontend framework. My goal is to evaluate the value of a read-only v-text-field, which displays a computed property based on user input. The implementation of my v-tex ...

What is the most efficient way to combine a parameter string within a JavaScript function and append it to an HTML string?

Welcome to my HTML code snippet! <div id="content"></div> Afterwards, I add an input to #content: $( document ).ready(function() { // Handler for .ready() called. var parameter = "<p>Hello</p>"; $("#content").appe ...

Grouping promises together using Promise.all

I came across this code snippet and need help understanding it: db.group.findOne({_id: id}).then((groupFound) => { var membersArray = groupFound.members; Promise.all(membersArray.map((member) => { return db .doneTod ...

Problem with CSS3 Target Selector

As I delve into the world of JS/HTML5/CSS3, I have been immersing myself in code examples from three different authors and combining and modifying them to enhance my learning. You can find my work-in-progress Pen, with references to the original authors, r ...

Refreshing select2 dropdown options dynamically with AJAX updates

I have a select dropdown for locations that is initialized using select2 on page load. I am looking to dynamically update the data in the dropdown at regular intervals using ajax calls. However, when I attempt to update the data in select2, the dropdown ...

In order to verify the dynamic components within the table

I need assistance with validating dynamically created textareas. In the code below, I am able to validate only the first row but struggling to do so for the second row. How can I get all the row values validated? Thank you in advance. To generate dynamic ...

Tips for transferring a value in JavaScript

There seems to be an issue with NULL VALUE ON $_SESSION in my compare.php file. Any ideas on how to resolve this? Thank you Below is the JavaScript function: $(function() { $('input[type=checkbox]').change(function() { var chkAr ...

What is the method for identifying the selected radio button that has been dynamically generated after clicking the submit button?

Despite this question being asked multiple times before, I am struggling to find a solution that fits my specific scenario. Initially, I have a static radio button that I create. The HTML code is as follows: <body> &l ...

Should Vue be reset before each Jest test?

I am currently working with Vue JS using @vue/test-utils and jest for my testing. In my tests, I call the following: let localVue = createLocalVue(); vueMount(MyComponent, { localVue: localVue, options }); The issue arises when referencing libraries that ...

What is the best way to convert a Date into the JSON format before sending it to the database?

I'm currently delving into backend development with Node.js, and I am in the process of connecting my backend to a MongoDB. Specifically, I am working on creating a User object that includes Birth Date as one of its properties. However, I am strugglin ...