"Approach for appending an additional element to an array item within a child component

I'm currently working on implementing two components, one acting as the parent and the other as the child. In the parent component, I have set up the data attribute like this...

data () {
    return {
      users: [],
    }
 } 

The users array within the parent component gets populated upon button click, and I am sharing this array with the child component. The issue arises when the child component attempts to add a user to this list - it works in terms of adding values to the passed-in props, but since the users array is declared under data in the parent, the component refreshes causing me to lose my previously added users. Is there a pattern or approach that would allow me to keep the existing values in the users array while also enabling additions from the child component?

Apologies if this query seems trivial, as I mentioned earlier, I am still quite new to this...

Edit: Here is the code for the parent component:

<template>
  <div id="app">
    <div>
      <button v-on:click="display()">Display users</button>
      <button v-on:click="displaySingleUserInput = !displaySingleUserInput">Add user</button>
      <div>
    </div>

    <ul v-if="errors && errors.length">
      <li v-for="error of errors">
        {{error.message}}
      </li>
    </ul>
    </div>

    <add-user v-on:submit_user="addUser" v-show="displaySingleUserInput"></add-user>
    <user-list v-bind:users="users"></user-list>             
</div>

</template>

<script>
import axios from 'axios';
import UserList from './components/UserList';
import AddUser from './components/AddUser';

export default {
  components: {
    'user-list': UserList,
    'add-user': AddUser
  },
  name: 'app',
  data () {
    return {
      users: [],
      errors: [],
      displaySingleUserInput: false
    }
  }, 
  methods: {
    display: function(string) 
    {
      axios.get(`users.json`)
       .then(response => {
          // JSON responses are automatically parsed.
          this.users = response.data.users
      })
      .catch(e => {
        this.errors.push(e)
      })
    },
    addUser: function(id) {
      this.users.push({firstname: "John", lastName: 'Jones'})
        },
  }
}
</script>

Child component:

<template>
    <div id="singleUserAdd">
      <form id=addUser aria-label="single user add">
        <button v-on:click="submit()">Submit</button>
        <button>Cancel</button>
      </form>
    </div>

</template>

<script>

export default {
  data() {
    return {
    }
  },
  methods: {
    submit: function() {
          this.$emit('submit_user', 1)
        }    
  }
}
</script>

Answer №1

Assuming there is a method named addUser in the child component :

   addUser(){
     this.$emit("addusr",this.newuser);
    }

In the parent component :

   <child-comp @addusr="addNewUser" />

    ...
   addNewUser(newuser){
        this.users.push(newuser);
     }

Answer №2

It appears that I overlooked

<form v-on:submit.prevent="onSubmit" 

in order to prevent my page from refreshing

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 storing Vuex state in sessionStorage a secure practice?

I am currently developing a web app with Vue.js/Vuex, but I am facing an issue where the state is lost when the user refreshes the page. I have attempted to address this by persisting some states in sessionStorage, however, I have come to realize that use ...

Combining the power of Django on the back end with a sleek React front end

The concept Embarking on the creation of a social media platform, I initially developed basic static pages using Django templates. These pages encompassed essential features like user profiles, status feeds, search functionality, and event listings. Howev ...

Using NodeJS and Express together with Ajax techniques

I am currently developing a web application that utilizes Ajax to submit a file along with some form fields. One unique aspect of my form is that it allows for dynamic input, meaning users can add multiple rows with the same value. Additionally, the form i ...

Hide and show submenus with jQuery while ensuring that the initial submenu remains visible, along with the main menu

I am struggling to figure out how to make the first message active by default along with its corresponding menu selection in my navbar. I have implemented a show/hide functionality on the main menu click, but currently only the menu is being set as active ...

Automatically adjust focus to a specific browser tab

Having trouble setting the auto focus on a tab when the page loads. I've created a fiddle where I attempted to set focus on the tab with class="test". Any ideas on what I might be doing wrong? http://jsfiddle.net/qL2W4/2391/ <div id="mydiv"> ...

Changing the css value using jquery is ineffective

When clicking the 'Design Custom Cables & Order Online' button, I aim to have the step 1 accordion content collapse and instantly expand the step 2 content. However, upon applying jQuery, the step 2 content does not expand immediately and the ste ...

Show image in ReactJS using flask send_file method

Using Flask's send_file function, I send an image to the client in the following way: @app.route('/get-cut-image',methods=["GET"]) def get_cut_img(): response = make_response(send_file(file_path,mimetype='image/png')) respon ...

We are experiencing difficulties rendering flash messages in Expressjs with Handlebars(hbs) and express-messages using flash-connect

I'm working on an express app and I want to display flash messages when a user signs up using a form. The technologies I am utilizing include Node.js, Express.js, Handlebars(hbs), connect-flash, and express-messages. To make finding errors easier, I ...

Establish a function within an interface using the name obtained from a constant in Typescript

How can I define functions within an interface using constants as function names? I have a const array containing event names and I want to create an ServerToClientEvents interface for SocketIO. I can define a function like this and it will work: interfac ...

Removing SESSION variables upon closing a tab

Currently, I am facing a challenge in finding a suitable solution to clear session variables when the tab is closed. Even after exploring various options, the closest method I found involves using the "onbeforeunload" function in JavaScript. <body onbe ...

SurveyJS Not Appearing as Intended

Having an issue integrating surveyjs with Laravel and Vue. When attempting to fetch the survey from an API, it's not working as expected. The data is being retrieved from a Laravel controller. https://i.sstatic.net/IouUF.png surveyshow.vue <templ ...

Is there a way to manipulate the triangular side zones on an icosahedron so that they vary in size without altering the overall shape of the object?

Is there a way to create an icosahedron that rotates while the triangular sides increase in size, similar to what is shown in this video: Watch here. Check out this JavaScript code using THREE.js THREE.IcosahedronGeometry = function ( radius, detail ) { ...

Condense a lineup of names into only two rows

I have a challenge where I need to showcase a list of names separated by commas, pulled from an array in my React component. The HTML output should appear as follows: <div> <span>Liza</span>, <span>Eric</span>, <span>Mic ...

Determine the dimensions of a div element in IE after adjusting its height to auto

I am currently working on a JavaScript function that modifies the size of certain content. In order to accomplish this, I need to obtain the height of a specific div element within my content structure. Below is an example of the HTML code I am dealing wit ...

What is the proper way to utilize document.getElementById() within a standalone js file?

As I dive into learning web development for the first time, I've decided to keep my scripts organized in separate files. However, I'm facing a challenge when trying to access elements from these external files. Below is a snippet of the JavaScri ...

Leveraging various libraries in React

My query revolves around a React application where I have integrated Material UI for only two components. Despite installing the entire Material UI library, will this lead to an increased bundle size for my application? Or does the build process only inc ...

Utilizing a for loop to add div elements

I have a HTML form in my code where the user fills out information, including entering a value in the "member" field and clicking a button to generate additional copies of the 'sector_prop' div. The form section is - Number of Sectors (L ...

Encountering a "Duplicate identifier error" when transitioning TypeScript code to JavaScript

I'm currently using VSCode for working with TypeScript, and I've encountered an issue while compiling to JavaScript. The problem arises when the IDE notifies me that certain elements - like classes or variables - are duplicates. This duplication ...

Retrieving exclusive npm packages from an npmjs user

I am currently facing a challenge with transferring all of our npm modules from npmjs.com to a new location. The issue is that our modules are saved under a private npm user account, making it difficult for me to programmatically access and consume all the ...

Load container events post ajax data retrieval

# Update: The answer can be found at the bottom of this question. # I am encountering the following problem: I have developed a function to load all events/plugins that are loaded on a specific event. Initially, these get loaded on the "body" element, ...