Sobes.tech
Middle

Kuidas edastada andmeid või meetodeid lapsekomponendist vanemkomponendile Vue-s?

sobes.tech AI

Vastus AI-lt

In Vue.js, the event mechanism is commonly used to transfer data or call methods from a child component to a parent.

The child component can send an event with the necessary data using $emit, and the parent component listens for this event and reacts to it.

Example:

<!-- Parent component -->
<template>
  <ChildComponent @custom-event="handleCustomEvent" />
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: { ChildComponent },
  methods: {
    handleCustomEvent(payload) {
      console.log('Data from child:', payload);
    }
  }
}
</script>

<!-- Child component -->
<template>
  <button @click="sendData">Send data to parent</button>
</template>

<script>
export default {
  methods: {
    sendData() {
      this.$emit('custom-event', { message: 'Hello, parent!' });
    }
  }
}
</script>

This way, the child component does not directly call the parent's methods, but reports an event, and the parent decides what to do with it. This supports the principle of unidirectional data flow and simplifies state management.