Home > Back-end >  Vue3 - How call function from another component
Vue3 - How call function from another component

Time:11-05

I start working with Vue3 and created some basic app with adding items to list.

I have two componetnts: ItemList and ItemForm. Both are added to main App.vue component like that:

App.vue - simplified

<template>
  <ItemsList/>
  <ItemForm/>
</template>

In ItemsList I have prop called 'items'. And function addItem() for adding new items to list.

In ItemForm have form and on submit I want send this data from form to ItemsList component to update list view.

I checked few things and nothing works for me (I read that in Vue2 was EventBus which was used for such a situation). I don't wanna also learn some bad way to solve that problems so I ask you for help.

#EDIT

App.vue

<template>
  <div>
    <ItemsList/>
  </div>
  
  <div>
    <ItemForm/>
  </div>
</template>
    
<script setup>
import ItemForm from "@/components/ItemForm";
import ItemsList from "@/components/ItemsList";
</script>

ItemForm.vue

<template>
  <form v-on:submit="addItem">
    <input type="text" v-model="title"/>
    <textarea v-model="description"></textarea>
    <button>Add item</button>
  </form>
</template>
    
<script>
export default {
  data() {
    return {
      title: '',
      description: '' 
    }
  },
  methods: {
    addItem(e) {
      e.preventDefault();
    }
  }
}
</script>

ItemsList.vue

<template>
  <ul>
    <li v-for="item in items">
      <p><b>{{ item.title }}</b></p>
    </li>
  </ul>
</template>
    
<script>
export default {
  data() {
    return {
      items: []
    }
  },
  methods: {
    addItem: function(item) {
      this.items.push(item);
    }
  },
}
</script>

CodePudding user response:

You probably should use emits to share the data from the child component to the parent. I have set up a Vue3 Composition API example. Check it out here:

Parent:

<template>
<Comp @send-data="callback" />

<input v-model="myInput" />
</template>

<script setup>
import { ref } from 'vue'
import Comp from './Comp.vue'

const myInput = ref('')

const callback = data => myInput.value = data
</script>

Child:

<template>
<button
  @click="btnClicked()"
  v-text="`Click to send data`"
/>
</template>

<script setup>
import { ref } from 'vue'
  
const emits = defineEmits(['sendData'])

const btnClicked = () => emits('sendData', 'some data')
</script>

* If you share some code, we can help you better and write better examples that get near what you want to achieve too.

CodePudding user response:

I found solution for my problem: https://pinia.vuejs.org/

Maybe someone will need this info.

  • Related