Fill the input fields with information stored in the vuex state within a vue component

Looking at the code snippet from my app component below:

<template>
  <div>
    <h3>Basic</h3>
    <div v-for="(field, index) in basics" :key="index">
    <input v-model="basics.name" placeholder="Name" type="text">
    <br>
    <br>
    <input v-model="basics.email" placeholder="Email" type="email">
    <br>
    <hr/>
    <button @click.prevent="addField">Add</button>
    <button @click.prevent="removeField(index)">Remove</button>
    <br>
    <button @click.prevent="back">Back</button>
    <button @click.prevent="toNext">Next</button>
  </div>
  </div>
</template>
<script>
import { mapActions } from "vuex";
export default {
  name: "Basics",
  data() {
    return {
      basics: [{
        name: "",
        email: ""
      }]
    };
  },
  methods: {
    ...mapActions(["addBasicData"]),
    addField(){
      this.basics.push({
        name: "",
        email: ""
      });
    },
    removeField(index){
      this.basics.splice(index, 1);
    },
    toNext() {
      this.addBasicData(this.basics);
      this.$router.push({ name: "Location" });
    },
    back() {
      this.$router.back();
    }
  }
};
</script>

After submitting the form and clicking the next button, the data is stored in the state and we are redirected to the "Location" route.

However, upon clicking the back button in the "Location" route, we return to the "Basic" route with empty form fields, even though they are bound to the data object.

How can I retain the input field values when returning to the same route?

You can view a working replica of the app here: codesandbox

Answer №1

<div v-for="(field, index) in basics" :key="index">
    <input v-model="basic.name" placeholder="Name" type="text">
    <input v-model="basic.email" placeholder="Email" type="email">
    <button @click.prevent="removeField(index)">Remove</button>
</div>
<hr/>
<button @click.prevent="addField">Add</button>
<br>
<button @click.prevent="back">Back</button>
<button @click.prevent="toNext">Next</button>

methods: {
    addField() {
        this.$store.commit('addBasic',{name:"",email:""} )
    },
    removeField(index) {
        this.$store.commit('removeField',index )
    },
    toNext() {
        this.$router.push({ name: "Location" });
    }
},
computed: {
    basic:{
        get() {
          return this.$store.getters.getBasic;
        }
     }
}

store.js

// ...
state: {
    basic:[{name:"Jonny",email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="761c1918180f361b171f1b385f1b">[email protected]</a>"}, 
           {name:"Bonny",email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="50123f3e3e29103d313f7d3a3e">[email protected]</a>"}]
}
mutations: {
    addBasic(state,value) {
        state.basic.push(value)
    },
    removeField(state,index ){
        state.basic.splice(index,1);
    }
 }  

There are different ways to achieve the same result. You can also map the mutatations and call them directly in the click event. https://vuex.vuejs.org/guide/mutations.html https://vuex.vuejs.org/guide/forms.html

The add field button is placed outside of the loop for better functionality.

The method addBasicData is not necessary in this case.

Answer №2

Here's a technique that seems to do the trick:

  mounted() {
    // don't mind this line
    let original = this.$store.state.Basics.basics;
    if (original) {
      this.basics.name = original.name;
      this.basics.email = original.email;
    }
  }

If you have any better methods for achieving the same result, I would be grateful to learn them. I attempted using mapState but it wasn't successful

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

Is there a way to perform a nextAuth sign in using Postman?

I am currently working on implementing user authentication using NextAuth. The authentication works perfectly within my webapp, but now I want to test the sign-in functionality using Postman so that I can share the login endpoint. Below is the configuratio ...

A method for consolidating multiple enum declarations in a single TypeScript file and exporting them under a single statement to avoid direct exposure of individual enums

I am looking to consolidate multiple enums in a single file and export them under one export statement. Then, when I import this unified file in another file, I should be able to access any specific enum as needed. My current setup involves having 2 separ ...

What makes using $(selector).post() and $.get() in jQuery AJAX so valuable?

While browsing w3school, I came across a discrepancy in the definition of AJAX post and get. Post: $(selector).post(URL,data,function(data,status,xhr),dataType) Get $.get(URL,data,function(data,status,xhr),dataType) Why is there a post method with sel ...

Is it possible to maintain the sidebar while eliminating the scrolling JavaScript?

Looking to recreate the image display style on Facebook where pictures appear in a lightbox format. The challenge I'm facing is figuring out how they manage to have the sidebar with no visible scroll bar inside... If you want to see this for yourself ...

Issue with VueJS: Cannot modify a component property within a watcher function

I am currently developing a Vue 2 Webpack application that utilizes Vuex. My aim is to update the local state of a component by observing a computed property which retrieves data from the Vuex store. Here's an excerpt from the <script></scrip ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

Unable to display image in Vuetify data table slot

I'm facing an issue with displaying images in a Vuetify data table column. Instead of the actual image, only the image URL is showing up, such as "9384053.jpg". How can I use slots in Vuetify to properly display the image? My array, Segment ...

Navigating a double entry validation in a Java script prompt while utilizing Selenium

Can someone please assist me with the following scenario: I need to complete a double entry check prompt/alert that contains two text boxes. The task is to fill in these two text boxes and then click on the OK button. Potential solutions attempted: I tr ...

Retrieve Data from Form Using PHP and Ajax

I currently have a form on my HTML page that looks like this: <form id="submission" action="testresponse.php" method="post"> <input id="URL" name="URL" type="text"> <button name="Submit" type="submit">Subm ...

Error message: The module '@project-serum/anchor' does not export the object 'AnchorProvider' as intended

I encountered an issue while attempting to run my react application. The issue: Attempted import error: 'AnchorProvider' is not exported from '@project-serum/anchor'. The import declaration in my code: import idl from './idl.json ...

navigation through sibling views using query-based route in ui-router

Imagine an app with two sides: "left" and "right", each with tabs. The application's URL structure is formatted like this: app/splitscreen/?leftTab=1&rightTab=1 Currently, the HTML template is set up as follows: <!-- splitscreen.tpl.html --& ...

What is the best way to transmit a data attribute within a Vue.js select option?

Is there a way to pass the test attribute of a select object to a function when it changes? I'm able to pass the value without any issues, but using e.target.test returns undefined. Any ideas on how to achieve this? <select v-model="prog.progr ...

Take a sequence of multiple words and combine them into a single string with hyphens in between

I've been working on a WordPress website and I created a JavaScript function that adds a class to the body tag, allowing for different backgrounds based on the category. It works perfectly fine when the category is a single word, but encounters issues ...

How about we display the Extents Algorithm?

Oh wise and knowledgeable coding community, I come seeking your expertise... I am working with the three.js library and facing a challenge in implementing a 'show extents' button. This button should adjust the camera position so that all objects ...

Having trouble accessing the value of an object within a nested array object

Looking for a way to extract the object value from a nested array object using JavaScript? If the sourcecountry matches the country in the object, it should return the corresponding payment service. Here is what I have attempted: function getValue(source ...

Visible center of the HighMaps display

I want to display a map of the USA with only certain states visible, such as those on the east coast. Is there a way to resize the map area dynamically to show only the selected states? For example, when I try to display just the east coast states, the fu ...

How can I determine the Windows service pack version directly from my web browser?

Is there a method to determine the installed service pack from the browser? It doesn't seem to be available in System.Web.HttpBrowserCapabilities in asp.net. I am looking for a solution to alert users about the necessity of updating to XP Service Pack ...

Having trouble retrieving the data property from the parent component within the child component slot

I am facing an issue with my Vue components. I have a rad-list component and a rad-card component. In the rad-list component, I have placed a slot element where I intend to place instances of rad-card. The rad-card component needs to receive objects from t ...

How can the properties in a document be updated in Mongoose only if they are present in the request?

My usual process for updating a document involves the following steps: Model.findById(id) .then((doc) => { doc.fName = req.body.fName ? req.body.fName : doc.fName; doc.lName = req.body.lName ? req.body.lName : doc.lName return doc.s ...

Following the execution of an AJAX request, the jquery script fails to run

I've encountered an issue with my website that utilizes pagination, filtering with jQuery and AJAX. Everything was functioning smoothly until I decided to switch my links to JavaScript links. When on the homepage without any filtering or pagination a ...