Tips for maintaining an updated array's consistency on page refresh in Vue.js?

HelloWorld.vue

Dynamic routing in Vuejs:

<template>
  <div>
    <b>Vuejs dynamic routing</b>
    <div v-for="item in items" :key="item.id">
      <b>{{ item.id }}.</b> &nbsp;&nbsp;&nbsp;
      <router-link :to="{ name: 'UserWithID', params: { id: item.id, item } }">
        {{ item.val }}{{ item.kk }}
      </router-link>
    </div>
    <br /><br /><br />
  </div>
</template>

<script>
import { data } from "../data";
export default {
  name: "HelloWorld",
  data() {
    return {
      items: data,
    };
  },
};
</script>

User.vue

Edit user details form:

<template>
  <div>
    <form>
      <label>Val:</label><br />
      <input type="text" id="val" name="val" v-model="val" /><br />
      <label>kk:</label><br />
      <input type="text" id="kk" name="kk" v-model="kk" /><br /><br />
      <button @click="updateData">submit</button>
    </form>
  </div>
</template>

<script>
import { data } from "../data";
export default {
  name: "User",
  props: {
    item: {
      required: true,
      type: Object,
    },
  },
  data: function () {
    return {
      val: this.item.val,
      kk: this.item.kk,
    };
  },
  methods: {
    updateData() {
      const id = this.$route.params.id;
      let newData = data.find((value) => value.id === id);
      newData.kk = this.kk;
      newData.val = this.val;
      this.$router.push({ path: "/" });
    },
  },
};
</script>

main.js

Vue Router setup:

import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld.vue";
import User from "./components/User.vue";

// Vue Router Configuration
Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    { path: "/", name: "User", component: HelloWorld, props:true },
    { path: "/User/:id", name: "UserWithID", component: User, props:true }
  ]
});

Vue.config.productionTip = false;

new Vue({
  router,
  render: (h) => h(App)
}).$mount("#app");

This is my complete working code with dynamic routing and user details editing functionality. If you encounter issues with page refresh resetting updated array values, consider using Vuex or local storage to persist the changes even after a refresh.

Answer №1

Every time your app refreshes, it goes through a re-render process. In your HelloWorld.vue file, you are fetching data from a local file, which is why you keep getting the same array with each refresh.

To display the updated array after a refresh, you will need to save the data in either localStorage or sessionStorage. Check if the data exists there and use that instead of relying on the data from the local file.

The state is not preserved upon refresh, so it's essential to store it somewhere persistent.

If you plan to use vuex, you can retain the data even after a refresh by utilizing vuex-persistedstate. For more information, refer to: Vuex state on page refresh

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

Angular does not alter the focus when a new component is loaded

Currently, I am working on resolving an accessibility issue with a screen reader in an Angular2 web application. When componentA (code shown below as Before) is loaded in Chrome, the entire browser window gains focus and the screen reader narrator announce ...

Is there a way to use moment js to change the date format to just show the month and year?

Want to transform the date time format using momentjs 2017-02-01T00:00:00.000Z into 02-2017 ( month-year ) Looking for a way to change the date format to display only month-year using momentjs? I attempted it like this: var MnthYr = moment(2017-02-01 ...

Unable to reach the prototype of the object

I am encountering an issue while attempting to access the object's prototype in a Node.js code. The objective is to send this object through an API so that users can utilize its methods. The problem lies in the fact that the returned object only inclu ...

Using the angular function directly is not possible without using setTimeout

My goal is to maintain the functionality of the back button in our application. We have implemented a back button that, when clicked, should preserve all the values selected or filled out by the user in the form. This task is being carried out in an MVC fr ...

Storing a photo taken with a camera to a local directory on the computer

Currently, I am utilizing HTML5 inputs to capture a picture from the camera by using the code below: <input id="cameraInput" type="file" accept="image/*;capture=camera"></input> Subsequently, I am obtaining the image in blob format and manip ...

Encountering RangeError with the Number() function on my express.js server

I'm working with an HTML form that looks like this: <form class="" action="/" method="post"> <input type="text" name="num1" placeholder="First Number"> <input type= ...

Stop the Bootstrap 5 accordion from expanding when the spacebar is pressed in the header text input

Within my React app using react-bootstrap, I have implemented an accordion component that expands or collapses based on the user's interaction with a text input located in the AccordianHeader component. Interestingly, whenever the spacebar is released ...

Vue.js V-for not rendering any content

I am currently working on populating an array with objects retrieved from an API. The objects are being fetched successfully, but I am facing issues when trying to display them using v-for in the array. Below are my data variables: data() { return { ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

Using HTML5 Canvas with Firefox 4: How to Retrieve Click Coordinates

Lately, I've been diving into creating HTML5 Video and Canvas demos. Initially, my focus was on optimizing them for Chrome, but now I'm shifting my attention to Firefox and Safari as well. One particular demo I'm currently working on involv ...

Node.js is throwing an error "Unexpected token v in JSON at position 0" which

I'm currently working on developing PHP code within the Google App Engine flexible environment. Specifically, I am facing some challenges in setting up the Firebase SDK Admin for the web version. My main struggle lies with the following block of code ...

Convert a multidimensional array into a string using JavaScript

Currently, I'm in the process of generating an invoice for a collection of books and my intent is to submit it using ajax. However, when attempting to json encode the array of books within the invoice, I am encountering a setback where the value keeps ...

Using NextJs <Script> is only effective after a page has been reloaded

Currently delving into the world of NextJS and encountering an issue with integrating a third-party ebay script onto one of my route pages. The script only seems to appear sporadically upon reloading the page. However, when navigating to the store page via ...

How to choose `optgroup` in Vue 1.x

In previous iterations of vue.js, developers had the ability to generate a dynamic select list utilizing optgroups similar to the example found here. In the latest versions of vue, the documentation suggests using v-for within the options instead of optgr ...

Removing a Div with Dynamic Parameters

I'm struggling to implement a feature in my form that allows the user to add multiple entries, but I'm having trouble with the removal aspect. Here is the JavaScript code: var i = 1; var divContent = document.getElementById ...

Adjust the camera in threejs to be positioned inside a different object

My goal is to adjust the camera controlled by trackballControl to match the position of an object. Currently, it's functioning correctly but as demonstrated in this example, each time the camera changes its position, the z value also changes, which i ...

Angular - Brilliant time selection tool (BTS) The TimePicker feature fails to automatically switch to selecting minutes after choosing the hour

I'm currently implementing the Amazing time picker in my app and I'm facing an issue where it doesn't automatically switch to minutes after selecting the hour. component.html <input type="time" atp-time-picker formControlName="time" cla ...

There appears to be an issue where the session object cannot be retrieved by the Struts2 action

I have a struts2 action that is invoked by a JavaScript function. The JavaScript function uses uploadify to enable multiple file uploads: <script type="text/javascript"> $(document).ready(function() { $("#fileupload").uploadify({ ...

The impact of a variable in a function with XMLHttpRequest

How does the XMLHttpReqeust variable impact the functionality of the following code snippets? function getHTTPObject() { if (typeof XMLHttpRequest == "undefined") { XMLHttpRequest = function () { try { return new Ac ...