Utilize data from a dynamically loaded component within a parent component in Vue.js

In my Vuejs application, I've implemented a wizard-type flow with dynamically loaded components. The parent component contains the Save button, while the child components have all the text fields. Upon clicking the Save button, I need to achieve two main tasks:

1) Load the next component (working currently) 2) Extract data from the text field(s) within the child component and store them in Vuex.

Below is the code snippet for the parent component:

<template>
<div>
  <component :is="selectedComponent"></component>
  <span @click="changeComponent(selectedComponent)" class="action button save">Save</span>
</div>
</template>

<script>
import auth from '@/api//auth'
import Establishment from '@/onboarding/components/OnboardingEstablishment.vue'
import Account from '@/onboarding/components/OnboardingAccount.vue'
import Vendor from '@/onboarding/components/OnboardingVendors.vue'
import Location from '@/onboarding/components/OnboardingLocation.vue'
import Menu from '@/onboarding/components/OnboardingMenu.vue'

export default {
  data () {
    return {
      accountName: '',
      selectedComponent: 'account'
    }
  },
  components: {
    establishment: Establishment,
    account: Account,
    vendor: Vendor,
    location: Location,
    appMenu: Menu
  },
  methods: {
    changeComponent (current) {
      const componentFlow = {
        account: 'establishment',
        establishment: 'location',
        location: 'vendor',
        vendor: 'appMenu'
      }

      var nextComponent = componentFlow[current]
      this.selectedComponent = nextComponent
    },
    updateState () {
      // Write the data from the element to the state.
    }
  },
  mounted () {
    auth.getAccountDetails()
      .then(response => {
        this.accountName = response.data.email
      })
  }
}
</script>

As an illustration, here is OnboardingAccount.vue, one of the dynamically loaded components:

<template>
  <div>
    <h1>Hey {{ accountEmail }}</h1>
    <p>Let's start at the top.</p>
    <p>What do you want to name your Account?</p>
    <input :value="accountName" type="text" />
    <p>Note: Your account name is the top level of your management. Additional teams or establishments can be added under this account name.</p>
  </div>
</template>

<script>
import auth from '@/api/auth'
import Establishment from '@/onboarding/components/OnboardingEstablishment.vue'
import Account from '@/onboarding/components/OnboardingAccount.vue'
import Vendor from '@/onboarding/components/OnboardingVendors.vue'
import Location from '@/onboarding/components/OnboardingLocation.vue'

export default {
  data () {
    return {
      accountEmail: '',
      accountName: ''
    }
  },
  components: {
    establishment: Establishment,
    account: Account,
    vendor: Vendor,
    location: Location
  },
  mounted () {
    auth.getAccountDetails()
      .then(response => {
        this.accountEmail = response.data.email
      })
  }
}
</script>

The challenge I am facing is accessing the value from the OnboardingAccount component when clicking the Save button in the parent Onboarding component to write the data to the Vuex store. Any insights on how I can accomplish this task would be greatly appreciated.

Answer №1

To maintain the state for every component, consider storing them in the parent component and passing them down as props. Trigger events like @change or @blur on input actions to emit an event. This standard component communication method can become more complex when dealing with dynamic components, requiring careful handling of props and events.

For cleaner prop passing to dynamic components, use v-bind on a whole object rather than individual variables/properties. You can structure this object to contain props for each dynamic component, ensuring a tidy component tag. Each child component can then extract the relevant property from the props object and utilize the data accordingly. To handle events sent back from children, set a generic event on the component tag (e.g., childEvent) for dynamic components to report any state changes, updating the parent component's state with the modified props. This approach simplifies saving data since all information resides within the parent component.

On another note: While you are effectively using dynamic components, consider enhancing your approach by incorporating webpack's dynamic imports. By doing so, you eliminate the need to manually import and declare each component. Check out this insightful article for further details.

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

Utilize Element UI autocomplete to transfer data into a VueJS-powered table's input fields

I am currently working on designing an invoice form using the Element UI framework. I have successfully integrated an autocomplete feature that retrieves data from the loadAll array. Upon clicking the add button and selecting an item_name from the autocomp ...

What is the process for setting up basic http authorization using angular.js?

My backend setup follows a structure similar to what is explained in this article. I am looking to make a GET request using angular.js, just like curl does it, with authorization via HTTP headers: $ curl -u miguel:python -i -X GET http://127.0.0.1:5000/a ...

Update the contents of a webpage using AJAX

Can anyone help me with loading likes into a div using AJAX every second? I want the page's URL to be likes.php?p=0 on page load, likes.php?p=1 after 1 second, likes.php?p=2 after 2 seconds, and so on. This is my code snippet: var loadLikes = func ...

Retrieve the current URL of an IFRAME

How can I easily retrieve the current URL from an embedded iframe? The user will be navigating through various web pages. I assume that some JavaScript code would be needed for this task. ...

What are some effective techniques for handling asynchronous operations while utilizing [displayWith] in an autocomplete

In my angular reactive form, I am struggling with an autocomplete functionality. I want to show the name (myObject.name) but use the ID (myObject.id) as the value. However, when the form is populated with existing values, there is a delay in retrieving th ...

Is it possible to repeatedly activate a function using onmousedown just like with onkeydown?

My goal is to have the onmousedown event trigger repeatedly when the left mouse button is held down, instead of just once upon clicking. Currently, it only fires a single time. wHandle.onmousedown = function (event) { console.log('mouse b ...

The battle of promises versus async await in Koa middleware

In an attempt to create a Koa middleware, I am faced with the decision of how to proceed based on certain conditions. If the condition is met, I want to move on to the next middleware. If it is not met, I need to stop the flow. Two possible approaches invo ...

Setting up a Laravel 7 and Vue single page application on a shared hosting environment

Hello, I'm facing an issue with my application that has a Vue front-end and Laravel 7 back-end. The problem is that I am unable to redirect to the login page and instead, it shows a blank screen. All the Vue files are stored in the resource/js folder ...

What methods can I use to conduct tests on functions in a Vuex module?

I am exploring a Vuex module named user. After successfully registering my module in Vuex, it is functioning as expected. // store/index.js import Vue from 'vue' import Vuex from 'vuex' import user from './modules/user' Vu ...

Exploring search capabilities within D3 graph nodes

After creating a JSON file with four tiers and utilizing D3.js's collapsing box format to visualize it (source: https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460), I've run into an issue. The problem stems from the sheer size of the J ...

Using AngularJS, learn how to populate array objects within a JSON object

I'm trying to load array objects from a multi-select control, then populate a model object called "name" with its name and age values. After that, I want to load an array from a select element into the model object. However, the ng-model directive on ...

Having trouble retrieving all JSON properties

I am facing an issue with my json structure where I am unable to access certain properties. I can only access the main properties like type, properties, and so on within that hierarchy level. However, I cannot seem to access icon, iconURL, or title. The da ...

Obtaining a variable from within two nested functions

I'm looking for a solution where I can retrieve a variable from inside a function using an ajax call. For example: function returnStuff(){ $.ajax({ //do something }).done(function(response){ return response; }) return response; } The ...

Illustrative demonstration of AngularJS

One way to showcase data using AngularJS is by triggering a function with a button click. Here's an example: <!DOCTYPE html> <html ng-app> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"& ...

Tips for removing markers from personal Google Maps

I am having trouble deleting markers from my Google Maps using my code. The markers array seems to be empty even after adding markers. Can anyone help me troubleshoot this? Thank you! When I use console.log(markers.length) in the removeMarkers() function, ...

Set my click event handler back to its default setting

I'm struggling with resetting a click function after it completes. How can I make sure it's ready to run again? $('body').on('click', '#ConfirmBet', function () { function randomImg() { var imgs = $(&apo ...

Manipulate an object in Three.js using the ObjLoader functionality

I'm currently working on manipulating an object loaded using OBJLoader in Three.js. The issue I'm facing is that while it's easy to manipulate the object once, I can't figure out how to do so during the animate loop or anywhere outside ...

The v-autocomplete component's watcher is not functioning as intended

Despite numerous attempts, I have been unable to get my watcher to work properly with the v-autocomplete component. <template> <v-app id="inspire"> <v-content> <v-form ref="form" v-model="valid" :lazy-validation="lazy"> ...

What is the most effective way to import and load three-orbitcontrols?

Has anyone tried implementing the OrbitControls function in conjunction with ReactJS? I have included a snippet of the code below: import React, { Component } from 'react'; import 'tachyons'; import * as THREE from 'react'; im ...

Unable to establish connection between Router.post and AJAX

I am currently in the process of developing an application to convert temperatures. I have implemented a POST call in my temp.js class, which should trigger my ajax.js class to handle the data and perform calculations needed to generate the desired output. ...