@Kist9

Как вызвать функцию в дочернем элементе из родителя app во vue.js?

Вот мой дочерний элемент и мне нужно вызвать в нем функцию sendMes1() из родителя
<template>
    <div class="RasForm">
        <div class="search1">
            <my-input v-model="mes.title" placeholder="Введите название" />
        </div>
        <div class="search1" >
            <my-input v-model="mes.body" placeholder="Введите текст"/>
        </div>
        <input type="file" id="file" ref="file" class="inputfile" @change="handleFileUpload" />
        <label for="file" class="myButton" >Прикрепить файл</label>
        <button @click="sendMes1" >
            Отправить рассылку
        </button>
    </div>
</template>

<script>
    import myInput from '@/components/UI/myInput';

    export default {
        components: {
            myInput,
        },
        data() {
            return {
                mes: {
                    title: '',
                    body: '',
                    file: '',
                },
            }
        },
        methods: {
            sendMes1() {
                this.mes.id = Date.now();
                let formData = new FormData();
                formData.append('file', this.file);
                this.$emit('sendMess', this.mes);
                this.mes = {
                    title: '',
                    body: '',
                    file: '',
                }

            },
            handleFileUpload() {
                this.mes.file = this.$refs.file.files[0];
            },
        }
    }
</script>

А это скрипт родительского элемента
<script>
    import myHeader from '@/components/myHeader';
    import myMessage from '@/components/myMessage';
    import userList from '@/components/userList';

    export default {
        components: {
            myHeader, myMessage, userList,
        },
        data() {
            return {
                messages: [

                ],
            }
        },
        methods: {
            sendMes(mes) {
                this.messages.push(mes);
            },
        }
    }

</script>
  • Вопрос задан
  • 113 просмотров
Пригласить эксперта
Ответы на вопрос 1
modelair
@modelair
unsocial
есть пара способов. это передача параметров через входящие слоты и expose с ref.

expose

будет доступно напрямую в рефке - child.value.publicMethod()

export default {
  expose: ['publicData', 'publicMethod'],
  data() {
    return {
      publicData: 'foo',
      privateData: 'bar'
    }
  },
  methods: {
    publicMethod() {
      /* ... */
    },
    privateMethod() {
      /* ... */
    }
  }
}


<script>
import Child from './Child.vue'

export default {
  components: {
    Child
  },
  mounted() {
  }
}
</script>

<template>
  <Child ref="child" />
</template>


v-slot

<div>
  <slot :text="greetingMessage" :count="1"></slot>
</div>


<MyComponent v-slot="slotProps">
  {{ slotProps.text }} {{ slotProps.count }}
</MyComponent>

expose with setup and defineExpose


parent.vue
<template>
  <div>
    <v-child ref="refChild" />
    <button @click="getDataFromChild">Call child function</button>
  </div>
</template>

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

const refChild = ref()

function getDataFromChild() {
  if (refChild.value) {
    refChild.value.childFunction()
  }
}
</script>


VChild.vue
<template>
  <div>{{ msgHello }}</div>
</template>
<script setup>
import { ref } from 'vue'

const msgHello = ref('Try to click on')

function childFunction() {
    msgHello.value = 'childFunction called!'
}
defineExpose({childFunction})
</script>

Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы