Reloading a page in Vue-Router after submitting a form

Learning Vue by creating a movie searcher has been quite challenging.

The issue I'm facing is that I'm using the same component for different routes with path params to fetch specific information. However, when I submit a form with a query for the API search, the page doesn't reload, and the component treats it as the previous route's info.

I've tried methods like router.go() and beforeRouteUpdate, but none of them seem to work.

See below for my code:

Router.js

import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import Detail from "./views/Detail.vue";

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: "/",
      name: "home",
      component: Home
    },
    {
      path: "/favorites",
      name: "favorites",
      component: Home
    },
    {
      path: "/results/:search",
      name: "results",
      component: Home
    },
    {
      path: "/detail/:id",
      name: "detail",
      component: Detail
    }
  ]
});

Cards.vue This component is called by Home

<template>
  <div class="cardContainer">
    <Filters />
    <div
      v-if="$store.state.movieList.length > 0"
      class="cardContainer-container"
    >
      <Card
        v-for="(item, index) in $store.state.movieList"
        :key="index"
        :id="item._id"
        :title="item.title"
        :img="item.image"
        :year="item.year"
        :description="item.description"
      />
    </div>
    <div v-else class="cardContainer-container">
      Not fun
    </div>
  </div>
</template>

<script>
import Card from "./Card.vue";
import Filters from "./Filters.vue";

export default {
  name: "cardContainer",
  components: {
    Card,
    Filters,
  },
  data() {
    return {
      path: this.$route.name,
      params: this.$route.params.search,
    };
  },
  beforeMount(){
    console.log("path", this.path);//this works when changing with navBars Links, but not with the search button

  },
  beforeRouteUpdate(to, from, next){
    console.log("I hope this works", to); //This doesn't work.
    next();
  }
};
</script>

SearchBar.vue

<template>
  <form class="searchBar" v-on:submit="onSubmit">
    <input type="text" v-model="search" />
    <button type="submit">
      Search
    </button>
  </form>
</template>

<script>
export default {
  name: "searchBar",
  data() {
    return {
      search: ""
    };
  },
  methods: {
    onSubmit() {
       // this.$router.go(`/results/${this.search}`) //does not work
      this.$router.push(`/results/${this.search}`);
      this.search = "";
    }
  }
};
</script>

UPDATE:

Solved the issue by adding a strange watch in the cards component and using @submit.prevent="submit" when submitting the search form.

cards.vue

<script>
import Card from "./Card.vue";
import Filters from "./Filters.vue";

export default {
  name: "cardContainer",
  components: {
    Card,
    Filters,
  },
  data() {
    return {
      path: this.$route.name,
      params: this.$route.params.search,
    };
  },
  beforeMount() {
    console.log("path", this.path); //dispatch
  },
  created() {
    this.$watch(
      () => this.$route.params.search,
      () => {
         this.params = this.$route.params.search;
        //dispatch 
      }
    );
  },
};
</script>

Still looking for a cleaner solution. If you have any ideas, please share. Thank you.

Answer №1

After submitting a form, the default action is to refresh the page. To prevent this behavior, you can use either of the following methods:

v-on:submit.prevent="onSubmit"

or

@submit.prevent="onSubmit"

Answer №2

I skimmed through your question quickly, but it seems like you may have to adjust the router-view key based on the URL (including URL parameters) in order to prevent caching when the URL changes. By default, URL params are not included in the cache.

<router-view :key="$route.fullPath"></router-view>

It is important to avoid app refreshes, even during form submissions. Additionally, consider using the .prevent method as suggested in another answer.

If you need to share data across multiple pages, consider using a store instead of query params. Alternatively, you can explore creating a basic store using the composition API without the complexity of vuex.

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

Troubleshooting the error "The 'listener' argument must be a function" in Node.js HTTP applications

I'm facing an issue resolving this error in my code. It works perfectly fine on my local environment, but once it reaches the 'http.get' call, it keeps throwing the error: "listener argument must be a function." Both Nodejs versions are iden ...

Vue encounters an issue when trying to access a specific field within an array of objects

Consider the following data structure: rules:[ 0:{ subrule1:'', subrule2:'', subrule3:'' }, 1:{ subrule1:'', subrule2:'', subrule3:'' } ...

It appears that the JavaScript array is able to modify itself autonomously

Currently, I am working on a project using P5.js where I am saving values in an array and then creating a copy of that array to manipulate. However, I have encountered an issue where manipulating the second array also changes the original one, and I cannot ...

The issue with Three.js responsive canvas is that it fails to properly adjust the size of the

I'm currently working on a threejs basic scene and attempting to create a responsive canvas for a full-screen experience. However, the mesh inside the scene is not resizing correctly as expected. Instead of remaining a cube, it distorts into a rectang ...

Upon initial login, React fails to retrieve notes

I developed a note-taking React app using the MERN stack with React Router DOM v6. When I initially visit the website, I am directed to the login page as intended. However, upon logging in, the page refreshes but does not redirect to the home page. This is ...

Challenges in rendering textures

Hello there, I'm encountering an issue with the way a texture is being rendered on an imported OBJ model. Below is an image showing how the texture currently appears: And here is how the texture should actually look when mapped to the object: Here ...

Ways to add a string to an array as a labeled object in javascript?

Is there a way to manipulate the array in imageCollection to achieve the format of the array in carouselPhotos as shown below? export default class HomeScreen extends Component { state = { imageCollection: [ { name: "P ...

When an onClick event is triggered in jQuery, generate a certain number of div blocks based on the available list items, such as image source and heading text

Is it possible to generate input fields dynamically based on a dynamic list with checkboxes, labels, text, images, etc.? I currently have a working solution for checkboxes and labels using the code snippet below: let $checkboxContent = $('.checkboxes ...

Using a variable name to retrieve the output in JavaScript

I created a unique JavaScript function. Here is the scenario: Please note that the code provided below is specific to my situation and is currently not functioning correctly. analyzeData('bill', 'userAge'); Function analyzeData(u, vari ...

Increasing numerical values within an array using JavaScript

My goal is to enhance the functionality of this visualization by being able to increase or decrease the nodes in the hidden layers. I have attempted to achieve this by adding the following code: I am facing difficulties in adjusting the number of hidden l ...

Is it more efficient to use Vue events or Vuex for transmitting data between components?

Working on a project where data needs to be shared between components in order to update a canvas element at 30-60fps for optimal performance on low-end devices. Currently utilizing Vuex store/get method for data transfer, but considering using events as ...

Loading screen while all files and audio are being loaded

My JavaScript code is responsible for displaying and playing audio on my website. Unfortunately, the load time of the page is quite slow. To address this issue, I decided to follow a tutorial on installing a preloader, which can be found at . Although I ...

Utilizing Arrays for Angular Data Binding with AJAX

I am currently experimenting with loading Ajax data into an array and then binding the array using Angular. Here is my code (I have some experience with KO, so I'm keeping it simple for now): Update: I managed to get it working. I believe the issue w ...

Avoiding ChartJS tooltips from being cut off

I've been exploring how to prevent chartjs from cutting off its tooltips, but I haven't been able to find a config option to address this issue. https://i.sstatic.net/Knzvd.png Here's what I've attempted so far: <script> ...

Adding more dynamic parameters to the external script in index.html using Vue.js

I am looking to pass username and userEmail from the getters/user method in Vuejs, which is within index.html. Here is an example of how I would like it to be passed: <script>window.appSettings={app_id:"appId", contact_name: "Alexander ...

Incorrectly modifying the _locals property while rendering a MySQL result in Express/Node.js leads to the error: "Cannot assign to read only property '_

I am currently using Handlebars to display data retrieved from a MySQL query. The route is set up as shown below: var query = "SELECT col1, col2, col3 FROM table WHERE section >= " + start + " AND section <= " + end + " ORDER BY col1 ASC"; connecti ...

Angular updating the parent model from within the transclude scope

I am puzzled by the concept of Angular transclude scope. I am attempting to create a collapsible directive, but it seems that binding inside the transclude scope does not affect the model of the parent unless I utilize an object like 'data'. < ...

Extracting information from a checkbox list displayed within an HTML table

I have a table with multiple rows and two columns in each row. The first column contains text, and the second column consists of checkboxes. While I was able to retrieve the values from the first column, I am struggling to fetch the values of the selected ...

Preventing FOUC when navigating away from a vue-flickity carousel/slider - the ultimate guide!

Currently, I've integrated the vue-flickity package by MetaFizzy's Flickity into my Vue application. Upon navigating away from a route containing a vue-flickity slider instance, there is a brief flash of unstyled slides visible in the document wh ...

What is the best way to display multiple levels of content within a v-for loop?

I am looking to create 20 expansion panels using a v-for loop to display the categories fetched from my JSON in each panel header. Additionally, I want to populate each expansion panel's content with the corresponding names retrieved from allItems dat ...