Tips on transferring information from a component to an instance in Vue

My goal is to retrieve data from a component and transfer it to a variable within my root Vue instance.

Vue Instance Configuration:

new Vue({
    el: '#root',
    data: {
        searchResultObject: ''
    },
    methods: {
        //....
    }
});

Global Component Configuration:

Vue.component('user-container-component', {
    props: {
        prop: null
    },
    template: '#user-container-template',
    data: function () {
        return {
            searchResultObject: ''
        }
    },
    methods: {
        dbSearch_method: function () {
            var self = this;
            $.ajax({
                url: 'Home/LocalSearch',
                type: 'GET',
                success: function (response) {
                    self.searchResultObject = response;
                },
                error: function () {
                    alert('error');
                }
            });
        }
    }
})

By clicking a button on the UI, the dbSearch_method is triggered, and that part is functioning correctly. I am specifically looking for a way to send the retrieved data to the searchResultObject in my root instance, rather than the component.

HTML Setup:

<button class="btn btn-link bold" v-on:click="dbSearch_method">{{item}}</button></li>

EDIT:

HTML Configuration:

<div id="root">
    //...
    <div id="collapse2" class="panel-collapse collapse">
        <ul class="list-group">
            <root-component v-for="item in customerObject"
                            v-bind:prop="item"
                            v-bind:key="item.id">
            </root-component>
        </ul>
    </div>
</div>
//...

<script type="text/x-template" id="root-template">
        <li class="list-group-item">
            <div class="bold">
                <button v-if="open" v-on:click="toggle" class="btn btn-link"><span class="glyphicon glyphicon-chevron-down" style="color: black"></span></button>
                <button v-else="open" v-on:click="toggle" class="btn btn-link"><span class="glyphicon glyphicon-chevron-right" style="color: black"></span></button>
                <button class="btn btn-link bold">{{prop.name}}</button>
            </div>
            <ul class="no-bullets" v-show="open">
                <park-container-component v-bind:prop="prop.parks"/>
                <admin-container-component v-bind:prop="prop.admins" />
                <user-container-component v-on:search-results-fetched="addSearchResults($event)" v-bind:prop="prop.admins" />
            </ul>
        </li>
    </script>

 <script type="text/x-template" id="user-container-template">
        <li class="list-group-item">
            <div class="bold">
                <button v-if="open" v-on:click="toggle" class="btn btn-link"><span class="glyphicon glyphicon-chevron-down" style="color: black"></span></button>
                <button v-else="open" v-on:click="toggle" class="btn btn-link"><span class="glyphicon glyphicon-chevron-right" style="color: black"></span></button>Users
                <button class="btn btn-primary btn-xs pull-right" data-toggle="modal" data-target="#inviteAdminModal">Add</button>
            </div>
            <ul class="no-bullets" v-show="open" v-for="item in prop">
                <li><button class="btn btn-link bold" v-on:click="dbSearch_method">{{item}}</button></li>
            </ul>
        </li>
    </script>

Script Configuration:

new Vue({
    el: '#root',
    data: {
        //...
        searchResultObject: ''
    },
    methods: {
        //...
        addSearchResults: function(data) {
            alert('adding');
            this.searchResultObject = data;
        }
    }
});
Vue.component('user-container-component', {
    props: {
        prop: null
    },
    template: '#user-container-template',
    data: function () {
        return {
            open: false
        }
    },
    methods: {
        toggle: function () {
            this.open = !this.open;
        },
        dbSearch_method: function () {
            var self = this;
            $.ajax({
                url: 'Home/LocalSearch',
                type: 'GET',
                success: function (response) {
                    self.$emit('search-results-fetched', response);
                },
                error: function () {
                    alert('error');
                }
            });
        }
    }
})

Answer №1

Assuming that the component user-container-component is located within an element with the id #root, your HTML structure would look something like this:

<div id="root">

    <user-container-component></user-container-component>
</div>

Within your user-container-component, you can emit an event in the success callback of your dbSearch_method AJAX request like this:

Vue.component('user-container-component', {
    props: {
        prop: null
    },
    template: '#user-container-template',
    data: function () {
        return {
            searchResultObject: ''
        }
    },
    methods: {
        dbSearch_method: function () {
            var self = this;
            $.ajax({
                url: 'Home/LocalSearch',
                type: 'GET',
                success: function (response) {
                    this.$emit('search-results-fetched', response);
                },
                error: function () {
                    alert('error');
                }
            });
        }
   }
})

To set up an event listener on the user-container-component in your HTML, you can do the following:

<div id="root">

    <user-container-component @search-results-fetched="addSearchResults($event)"></user-container-component>
</div>

In the root Vue instance, don't forget to add the addSearchResults method:

new Vue({
    el: '#root',
    data: {
        searchResultObject: ''
    },
    methods: {
        addSearchResults(data){
            this.searchResultObject = data;
        }
    }
});

Answer №2

If you want to pass the value to the parent component to listen to, you can emit it as an event:

$.ajax({
            url: 'Home/LocalSearch',
            type: 'GET',
            success: function (response) {
                self.searchResultObject = response;
                this.$emit('onSearchResult', response)
            },
            error: function () {
                alert('error');
            }
        });

Then, in the parent component, you can set up a listener to fetch the emitted value:

<user-container-component v-on:onSearchResult="parentListener"/>

Answer №3

To effectively manage data in a large project, consider utilizing vuex.

Alternatively, eventbus can be used for data transmission between components at the same level. Learn more here

In your specific scenario, using $emit would be appropriate.

dbSearch_method: function () {
        var self = this;
        $.ajax({
            url: 'Home/LocalSearch',
            type: 'GET',
            success: function (response) {
                self.searchResultObject = response;
                this.$emit('customEvent', response);
            },
            error: function () {
                alert('error');
            }
        });
    }

In the root vue instance, you can use $on to listen for the event being triggered. Learn more here

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

What is the best way to choose an item from a list nested inside a div?

Currently, I am facing the challenge of selecting an item from a list that is structured using a div For this task, I am utilizing WebDriver IO () <div class="selectize-dropdown demo-default select-class single" style="display: none; width: 196px; top ...

When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code ...

Enhancing user experience with Jquery datepicker and executing multiple actions on select

I am working on a form that includes a jQuery date selector and radio buttons structured in a table as shown below: <table> <tr> <td> <input type="text" id="5506_datepick_1"></input> </td> <td&g ...

The behavior of JS Array.push may catch you off guard

There seems to be an issue with the push function in my code. The problem lies in the last line of code shown below. export enum non_searchFieldsNames { language = 'language', categories = 'categories', subtitle = 'subt ...

Retrieve: proper authentication credentials were not provided

Whenever I make a request, everything works fine and I receive the data: const get_players = async()=>{ const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/') const data = await response.json() console. ...

I am unable to log in using bcryptjs, but I have successfully been able to register a

Hey there! So I'm diving into Nodejs and I've managed to create a simple login/register API. For password encryption, I'm using bcryptjs. Testing it out on postman, I can successfully register a new user. However, when attempting to login wi ...

Is it feasible to incorporate a third-party JavaScript file into a React application?

I have a JavaScript file from a previous MVC project that generates a basic table using ExtJS. Currently, I'm working on developing a new React application with a navigation bar and sidebar. My goal is to explore the possibility of importing the exis ...

Error message: Cannot bring in JavaScript category. TypeError: "class" does not work as a constructor

I'm encountering a strange problem when trying to import my class into another module. Everything works fine when I import the worker module in my start.js file and run the script smoothly. But, the issue arises when the socket module attempts to impo ...

How can you retrieve the preceding sibling using an Angular directive?

Currently, I am utilizing ELEMENTREF to interact with the DOM via Renderer2. Allow me to provide a simple example: import { Directive, Renderer2, ElementRef } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export c ...

[Vue alert]: Unable to locate component: b-field

Struggling to set up a codepen demo to showcase a CSS problem. Facing issues with Buefy's b-field component not being recognized in the console outputting a warning message: https://i.sstatic.net/vrI1D.png Installed packages in Codepen Settings: Her ...

Utilizing JSON data from Jade in local JavaScript: A comprehensive guide

Attempting to utilize a JSON object (the entire object, not just a portion) from Node via Jade in my local myScript.js. Here is what my Jade file looks like: span(class="glyphicon glyphicon-pencil" onclick="confirm(\"#{myJSON.taskid}\", \" ...

The function or attribute "registerUser" is not specified on the instance, yet it is being referenced during the rendering process

index.blade.php <div id="register"> ... <div> <button type="button" class="btn btn-primary" @click="registerUser">Add</button> </div> </div> manage.js var DomainUsers = { template: `...`, d ...

Function in React not being successfully passed down between functional components

I have been accustomed to using class components and now I am transitioning into functional components in order to become more proficient with hooks. However, I have encountered an issue where I am struggling to pass a function from one functional compone ...

Exploring the GitHub Repository API with React

I am currently developing a feature that allows users to enter a username and view all the github repositories for that user in a separate react component within a repolist component. Although I can retrieve the JSON data for all the repos, I am facing is ...

Exhilarating Javascript document with fresh lines and line breaks

In my current project, I am dynamically generating a JavaScript page using PHP and .htaccess to convert .php files into .js files. Everything is functioning properly, except for the output of the JavaScript code. For example: $data = array('one&apo ...

Delving into the World of ReactJS Routing Components and Rendering

I recently developed a basic booking app consisting of 3 essential files - App.js, Booked.js (1st child), and Details.js (2nd child). My current dilemma involves attempting to access App.js for the purpose of deleting data using the 2nd child (Detail.js). ...

Is it possible to include number padding in a Bootstrap number input field?

When using an input box like this: <input type="number" class="form-control" value="00001" /> Is there a way to make it so that when the arrow up key is pressed, it changes to 00002 instead of just 2? https://i.sstati ...

Different results can be observed when comparing the array ordering in JavaScript between IE8 and Chrome

The array presented with items listed in specific order: { "5":{ "Title":"Title A", "Desc":"Description A" }, "15":{ "Title":"Title B", "Desc":"Description B" }, "10":{ "Title":"Title C", "Desc":"Description C ...

Trying out the fetch api with Jest in a React Component: A step-by-step guide

As a newcomer to test driven development, I stumbled upon a section that talked about testing/mocking a fetch API. However, I am facing issues while trying to write my own test. In order to practice this concept, I created a simple weather app where I atte ...

What is the best way to retrieve the first item in owl carousel's content?

I need help creating a slider with two sections: top and bottom. My goal is to display the content from the bottom slider on the top slider. I tried adding a class to the first item element, but it didn't work. If anyone knows how to target the first ...