Tips for retaining component data while navigating between components in vue js

If I have two elements, the first one is named X:

<template>
<input  required type='text' v-model.trim="number">
<input type="date" v-model="date" >
<button @click='allData(number,date)'>ok</button>
 <table >
    <thead>
      <th>Details</th>
    </thead>
    <tbody>
      <tr v-for='info in infos'>
        <td @click="seeMore(info.id)" > {{ info.data.to }} 
</td> 
      </tr>
    </tbody>
  </table>
</template>

<script lang="js">
import axios from 'axios';
export default {
name: 'X',
props: [],
data() {
  return {
infos: [],
number: '',
date: new Date().toISOString().slice(0,10),
count:0
 }

},
methods: {
 allData: function(number,date) {
   axios.get(`/api/infos?number=${number}&date=${date}`)
     .then(response => {
       this.infos = response.data.list;
       this.count = response.data.count;
     })
     .catch(error => {
       console.log(error);
     });
 },
 seeMore (id) {
     this.$router.push({ name: 'Y', params: { id }});
   }, 
}
</script>

the 2nd element is called Y:

  <template>
  <div> {{details.data.add }}</div>
  </template>
  <script lang="js">
    import axios from 'axios';
    export default  {
     name: 'Y',
     props: [],
      mounted() {
       const id = this.$router.currentRoute.params.id;
    this.fetchInfoData(id);
   },
   data() {
    return {
     details: []
    }
  },
  methods: {
   fetchInfoData(id){
    axios.get(`/api/search/${id}`)
    .then(response => {
        this.details = response.data
    })
    .catch(error => {
        console.log(error);
      });
     },
    },
   } 
  </script>

I wish that when I navigate from component Y back to component X, the information of X related to the result in Y is still displayed without having to re-enter the date and number.

Answer №1

Exploring the realm of application state management can lead to various perspectives. While vuex is often recommended as a solution, I personally prefer keeping app state in a global JavaScript variable for simpler scenarios. By having Vue components reference this centralized source of truth outside of Vue itself, they can both display and modify the data as needed. For example, if your app state revolves around a contacts array, a component like B (which admittedly needs a better name) could simply add new rows to this array. Upon returning to component A, the page will automatically update to reflect the changes.

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

Having trouble receiving the response from PHP after making an AJAX request

Can you help me figure out why I'm not receiving any return value from the ajax data post? Take a look at my code and let me know where I might be going wrong. Here is a snippet of my jQuery code: $("#btnlogin").click(function(){ var email = $( ...

Persistent change issue with JQuery CSS function

Looking for some help with a button-bar div that I want to display only after the user clicks on a "settings" button. Currently, I have set the button-bar div to have a display:none property in my css file. However, when the settings button is clicked, t ...

Steps for making a cookie in Node.js using Socket.IO

I'm currently exploring the process of creating a cookie while utilizing socket.io. Although I have successfully figured out how to read cookies, I am struggling to find resources on how to actually create one. socket.on('test', async funct ...

Table Header Stays Put Without Shrinking or Expanding with Window Adjustment

I have a sticky table header that stays at the top when scrolling down on my web page. To achieve this effect, I followed the solution provided on css-tricks.com/persistent-headers/. However, I encountered an issue where the sticky table header does not ...

Chrome will automatically retry an AJAX POST request if it times out after 10 seconds

I am in the process of creating a React JavaScript application using a back end powered by Node.js and Express. The software versions being used are as follows: React: ^16.0.0 Node: v8.0.0 Express: ^4.14.0 Chrome: Version 63.0.3239.84 (Official Build) (64 ...

Is there a way to verify that a form field has been completed?

Currently, I am grappling with a method to clear a field if a specific field is filled in and vice versa. This form identifies urgent care locations based on the information provided by users. The required entries include the name of the urgent care facil ...

Can you iterate through each element that matches those in a different array?

As a beginner in Javascript, I may stumble upon some obvious errors, so please bear with me. My goal is to iterate through two arrays and perform a loop for each element that exists in both arrays. Currently, this is my code: if(obtainedCards.some( sp =& ...

Creating a sidebar navigation in HTML and CSS to easily navigate to specific sections on a webpage

Here's a visual representation of my question I'm interested in creating a feature where scrolling will display dots indicating the current position on the page, allowing users to click on them to navigate to specific sections. How can I achieve ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

Utilizing Express.js: A Guide to Fetching File Downloads with a POST Method

Although GET requests are successful, I am facing challenges when using POST to achieve the same results. Below are the different code snippets I have attempted: 1. app.post("/download", function (req, res) { res.download("./path"); }); 2. app.post ...

Divs are the preferred placeholders over inputs and textareas

For the past few weeks, I have been trying to tackle a problem with creating placeholders that guide users on where to type. My goal is to make these placeholders disappear when users start typing and reappear if the div is empty again. All my attempts so ...

What is the process for invoking a server-side Java function from HTML with JavaScript?

Can someone help me figure out the best way to invoke a Java method from HTML (I'm working with HTML5) using JavaScript? I attempted using Applets but that approach didn't yield any results. My goal is to extract the value from a drop-down menu i ...

Instructions for concealing and revealing a label and its corresponding field before and after making a choice from a dropdown menu

Currently, I am working on developing a form that will enable customers to input their order information. This form includes a selection list for payment methods, with three available options. If the user chooses either credit or debit card as the paymen ...

Uploading a collection of objects to Node.js for storage in a database with Mongoose

I have developed a ReactJS form that allows users to dynamically add form "parts" (sections with form input fields). Let me illustrate this concept with an example: <div> <input placeholder="Author" /> <input placeholder="Age" /> ...

Are Viewmodel contents empty after ajax request?

Currently working on an ASP.NET MVC application, I am in the process of developing a search page that showcases both the search box and the table of results simultaneously. To achieve this functionality, I have utilized Partial Views along with AJAX/JSON c ...

Tips for avoiding a form reload on onSubmit during unit testing with jasmine

I'm currently working on a unit test to ensure that a user can't submit a form until all fields have been filled out. The test itself is functioning correctly and passes, but the problem arises when the default behavior of form submission causes ...

When attempting to check and uncheck checkboxes with a specific class, the process fails after the first uncheck

I have a set of checkboxes and one is designated as "all." When this box is clicked, I want to automatically select all the other checkboxes in the same group. If the "all" box is clicked again, I would like to deselect all the other checkboxes. Currently ...

`Inquiry into AJAX form submission problem`

Here is the HTML markup and JS code for my signup page. I encountered an issue where, if I leave all text inputs blank and click submit for the first time, it validates and shows an error message. However, when I click submit a second time, it directly sen ...

Seeking clarification on how the Typescript/Javascript and MobX code operates

The code provided below was utilized in order to generate an array consisting of object groups grouped by date. While I grasped the overall purpose of the code, I struggled with understanding its functionality. This particular code snippet is sourced from ...

Using jQuery for Dragging and Dropping Elements within Dynamically Loaded Divs with

Is it possible to drag an element on the page into a droppable element inside an ajax loaded div? The code works fine when the droppable element is placed directly in the regular page, but not within the ajax loaded div. It seems like the issue may be rela ...