Ways to retrieve the child component prop using the parent component prop

After creating a component for form submission, I added another component for file uploads within it as shown below:

<booksmandala-originals-form
                :action="'{{ url('admin/booksmandala-originals') }}'"
                inline-template>

                <form class="form-horizontal form-create" method="post" @submit.prevent="onSubmit" :action="this.action" enctype="multipart/form-data" novalidate>
                    @csrf
                    <div class="card-header">
                        <i class="fa fa-plus"></i> Create
                    </div>

                    <div class="card-body">

                       <div class="form-group row align-items-center" :class="{'has-danger': 
                        errors.has('categories'), 'has-success': this.fields.published_by && 
                        this.fields.categories.valid }">
                         <label for="categories" class="col-form-label text-md-right" 
                           :class="isFormLocalized ? 'col-md-4' : 'col-md-2'">Select 
                           Categories</label>
                         <div :class="isFormLocalized ? 'col-md-4' : 'col-md-9 col-xl-8'">
                            <multiselect v-model="form.categories" tag-placeholder="Add this 
                              as new category" placeholder="Search or add a category" 
                              label="title" track-by="id" :options="{{ $categories->toJson() 
                               }}" :multiple="true" :taggable="true" @tag="addCategory" 
                              :close-on-select="false" name="categories[]"></multiselect>
                              <div v-if="errors.has('categories')" class="form-control- 
                             feedback form-text" v-cloak>@{{ errors.first('categories') }} 
                              </div>

                          </div>
                       </div>


                      <media-upload
                          :ref="'cover_uploader'"
                          :collection="'cover'"
                          :url="'{{ route('admin.upload.media', $folder) }}'"
                          :accepted-file-types="''"
                          :max-number-of-files="5"
                          :max-file-size-in-mb="100"
                          :accepted-file-types="''"
                          @if(isset($media))
                             :uploaded-images="{{ $media->toJson() }}"
                          @endif

                      </media-upload>




                    </div>

                    <div class="card-footer">
                        <button type="submit" class="btn btn-primary" :disabled="submiting">
                            <i class="fa" :class="submiting ? 'fa-spinner' : 'fa-download'"></i>
                            Save
                        </button>
                    </div>

                </form>

            </booksmandala-originals-form>

In the media-upload component, there is a JSON variable called data returned from the mentioned route. When submitting the main form, I want to capture that returned data in my controller.

The main Form (Booksmandala-original-form.js) contains the following code:

import AppForm from '../app-components/Form/AppForm';

Vue.component('booksmandala-originals-form', {
    mixins: [AppForm],
    data: function() {
        return {
            form: {
                title:  '' ,
                body:  '' ,
                published_at: '' ,
                enabled:  false ,
                slug : '',
                categories:[],
                tags: [],
                files:[],
            },
            mediaCollections: ['cover'],
        }

    },
    props : ['users','categories']

   });

I aim to store the JSON value obtained from the media-upload component into the data() section of my form.js so that it can be utilized in my controller.

Answer №1

One way to handle JSON data in your project is by creating a method within your booksmandala-originals-form component. This method can take the JSON object as an argument and store it in the necessary location. By passing this method as a prop to your child component, you can easily call it whenever needed.

Here's how you can pass the method as a prop:

<media-upload
   :jsonHandler="jsonHandler"
   >

In the script section of the parent component:

data () {
      return {
            myJsonData: null
      }
},
methods: {
    jsonHandler(jsonData) {
        this.myJsonData = jsonData;
    }
}

Within the child component, simply call

this.jsonHandler(<pass your data>)
.

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

When an image is opened in a modal, it causes the original image on

I recently created a website using HTML/CSS and JavaScript, and I incorporated a modal using Bootstrap 5. To add a unique touch, I used JavaScript to replace the standard "Save changes" button of Bootstrap with a random image inside the modal. However, I n ...

Reduce the value of a Perl scalar variable each time an ajax script is executed

My webpage features a header with a notification button that indicates the count of unarchived notifications using this Perl code snippet: @notices_posts = System::Notice->fetch_all_posts(userid => $user->userid(), visible => 1); @regular_post ...

Choosing a button element in Node.js using WebDriver-Selenium

On my html page for posting data to the server, I am attempting to automate a specific job by selecting a particular button. However, when using Selenium to select the "text2" button, I am encountering issues. <div id="cdk-overlay-17" class="cdk-ove ...

Issue with C# MVC JS functionality not functioning properly within Partial view following ajax validation

In my layout, I include my script code from the view. @if (IsSectionDefined("VSscript")) { @RenderSection("VSscript"); } Within the view, I define the script section @section VSscript { and set up an Ajax form that connects to a partial v ...

Pass data that has been asynchronously resolved from the parent component to the child component using props in Vue

Main component: <template> <div> <Nav :data="data" /> </div> </template> <script lang="ts"> // ... imports removed for clarity @Component({ components: { Nav: () => import('@/components/Nav.vue&ap ...

Tips for accessing store data within the mounted lifecycle hook in a Vuex component

In my project, I have the main root component called App.vue and another component named FileUploaderParent.vue. I am using a dispatch promise to store data in the Vuex store. The dispatch call is made under the mounted lifecycle hook. However, when I try ...

Label positioning for checkboxes

Is there a way to display the checkbox label before the actual checkbox without using the "for" attribute in the label tag? I need to maintain the specific combination of the checkbox and label elements and cannot use nested labels or place other HTML elem ...

AngularJS - Issue with retrieving the most recent entry during $routeChangeStart event

I am utilizing the $routeChangeStart function to redirect authorized users to specific URLs and prevent unauthorized access to special pages. In addition, I have dynamically generated pages that can be accessed via their unique page slugs. To achieve this ...

The Laravel 8 controller is unable to detect the presence of a JavaScript tool

I'm currently developing a website using Laravel 8 and I'm facing an issue with passing PHP variables into JavaScript. Initially, I attempted to include the variables in my Blade file like this: <script> let x = {{ $x }}; </script> ...

Prevent JavaScript script execution while scrolling or clicking

I have implemented a script for autoscrolling on my website. The idea is that when the user visits the site, there is an initial logo display followed by an automatic scroll after a set amount of time. $(document).ready(function () { setTimeout(func ...

When a login attempt is unsuccessful, I am redirected to /api/auth/error using next-auth

Currently, I am utilizing next-auth version 4.18.8 on my login page for the final project of my Fullstack JS course. It's worth noting that a more recent version is being used compared to what was taught in the course (next-auth v. 3). Upon entering ...

The complexities of stopPropagation() causing further confusion

I have encountered an issue with my code. It currently allows a dropdown functionality for a <ul> element, but when a child <li> is clicked, it also closes other menus of the same type. To fix this, I used an if clause to check if the clicked ...

Identify when a browser tab is closed and determine which specific tab out of all the open tabs was closed

Is there a way to identify when a browser or tab is closed in Angular/JavaScript? I would like to know if there are specific events that can be used for detecting these actions. Any advice, information, or code examples on this topic would be greatly app ...

Steps to ensure that ng-click event is not activated by elements within the container in AngularJS

Currently, I am facing the following scenario: <div ng-click="foo()"> <a ng-click="bar()">Bar</a> <p>Lorem Ipsun</p> </div> The issue at hand is that when I click on "Bar", both foo() and bar() functions are trigge ...

Issues arise when attempting to retrieve information in NextJS from a local API

One of my coworkers has created a backend application using Spring Boot. Strangely, I can only access the API when both our computers are connected to the same hotspot. If I try to access the other computer's API and port through a browser or Postman, ...

difficulties retrieving information with $http.jsonp

Here is the code snippet that I am working with: var url = 'http://someURL?arg1=test&arg2=test&callback=JSON_CALLBACK'; $http.jsonp(url) .success(function(data){ console.log(data.found); }); Despite receiving a status code of 200 o ...

Retrieving an array of JSON data from an HTTP response

Recently starting my journey with AngularJS for a project, I've encountered a challenge in extracting a json array from an http response to utilize in a list. Here's a glimpse of the response structure: { "DFH0XCMNOperationResponse": { "c ...

Creating a system for handling multiple users in my to-do app with MERN stack: What is the best approach

Currently, I am working on adding a feature that would allow multiple users to use my to-do app. However, I am uncertain about the most effective way to do this. Essentially, I want users to be able to create accounts, log in, and have access to their own ...

Rotating a rectangular sprite around a sphere in three.js while keeping a minimum distance

In a three.js environment, featuring a static camera, and a sphere positioned at 0,0,0, along with a rectangular sprite (such as a text label) of varying dimensions, I am seeking a 'threejs method' or formula to enable the rotation of the sprite ...

What sets jQuery apart from Node.js?

After experimenting with Node.js, I find myself still confused about the differences between jQuery and Node.js. My understanding so far is that Node.js allows for server-side JavaScript while jQuery serves as an abstraction library for client-side JavaSc ...