[Vuejs]-How to pass data from a component to an Instance in Vue

2๐Ÿ‘

โœ…

As you said the component user-container-component is inside element with id #root, assming your html to be like this:

<div id="root">

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

in your user-container-component emit an event in the succss 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');
                }
            });
        }
   }
})

in your html setup an event listener on the user-container-component like this:

<div id="root">

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

in your root instance add addSearchResults method:

new Vue({
    el: '#root',
    data: {
        searchResultObject: ''
    },
    methods: {
        addSearchResults(data){
            this.searchResultObject = data;
        }
    }
});
๐Ÿ‘คVamsi Krishna

0๐Ÿ‘

You can emit the value as an event for parent to listen to

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

then in your parent you can fetch it by setup a listener

<user-container-component v-on:onSearchResult="parentListener"/>
๐Ÿ‘คFan Cheung

0๐Ÿ‘

For a big project, you can use vuex to manage the data.

Or you can just use eventbus to solve the same level component data transmission.here

For your situation, I think it should use $emit.

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');
            }
        });
    }

and in your root vue instance,you can use $on to listen the event fire.here

๐Ÿ‘คshauvet

Leave a comment