lidersin
lidersin

Reputation: 49

vuejs props v-model to with getdata

I am a vuejs newbie, what i want to do may be simple but it seems too complicated to me. Example: What I wrote in the "vue-search" input makes a search in the VueSearch Component, but suddenly it empties the input. and "async search(event)"

I want to send the incoming data to the main component. because I will post there, I will put it in the "getData:[]" section of the main component.

Thank you in advance for your help.

<template>
<vue-search v-model="nameText"/>
</template>
<script>
import VueSearch from "./components/tools/VueSearch";

export default {
    data() {
        return {
            nameText: '',
            getData:[]
        }
    },
    components: {
        VueSearch
    }
}
</script>
<template>
    <div>
        <input type="text" :value="value" @input="search"/>
        <p>{{ DoubleDATA }} </p>
    </div>
</template>

<script>
export default {
    name: "VueSearch",
    data() {
        return {
            DoubleDATA: ''
        }
    },
    props: {
        value: String
    },
    methods: {
        async search(event) {
            if (event.target.value !== '') {
                const res = await this.callApi('get', 'search' + '?filter=' + event.target.value)
                if (res.status === 200) {
                    this.DoubleDATA = res.data;
                }
            }
        }
    }

}
</script>

Upvotes: 2

Views: 170

Answers (1)

Jonathan Bowman
Jonathan Bowman

Reputation: 1646

Try using $emit. There are lots of ways to accomplish this, from state management frameworks like Vuex, to a small, simple but effective event bus you make yourself.

From your child component, you can send data back up to the parent like:

// MyChildComponent.vue


<script>
    export default {
        methods: {
            sendToParent(data) {
                this.$emit('your-custom-event-name', data);
            }
        }
    };
</script>

You can then listen for your-custom-event-name on the parent, and react to it:

// MyParentComponent.vue


<template>
    <!-- $event is the data we are passing from the child component -->

    <my-child-component @your-custom-event-name="someMethod($event)"/>
</template>

<script>
    export default {
        methods: {
            someMethod(data) {
                // and here is your data from the child component!
                console.log(data)
            }
        }
    };
</script>

$emit is great if you just need to go one layer up to the parent, but if you need to broadcast more...broadly...then you would probably want to go the event bus or Vuex route.

Does this make sense? Give it a shot and let me know if you have any questions.

Upvotes: 1

Related Questions