Search code examples
javascriptvue.jsvue-composition-api

How to acces data and methods from defineExpose in vue


`I am trying to access the method from the child component to the parent component in Vue(composition api) , I have defined the method inside the defineExpose , but not able to access it within parent

Hero.vue ( ChildComponent)

<template>
  <section data-testid="hero-section" class="flex flex-row gap-2 justify-between ">
    <h1 class="text-xl font-semibold text-ds-dark-500">
      {{ greeting }}
    </h1>
    <div>
      <Input v-model="searchQueryValue" data-testid="hero-section-input" placeholder="Search across use case" licon="fas fa-search" liconClasses="text-dark-60% px-1" inputClasses="rounded-full !border-1 !border-dark-20%" @input="handleSearch" />
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, defineEmits, ref } from 'vue';
import useUserDerivedDetails from '~/composables/useUserDerivedDetails';
import Input from '~/components/Input.vue';
import { useTranslation } from 'i18next-vue';
import { getGreeting } from '../utils';

const emit = defineEmits(['search', 'clearSearch']);
const { t: $t } = useTranslation();

const { user } = useUserDerivedDetails();

const searchQueryValue = ref('');
const userName = computed(() => {
  const name = user.value.firstName || user.value.lastName || '';
  return `${name}`.trim();
});

const greeting = computed(() => {
  return $t(getGreeting(searchQueryValue.value, userName.value));
});

function handleSearch(e: Event) {
  emit('search', e);
}
function clearSearch() {
  searchQueryValue.value = '';
  emit('clearSearch');
}

defineExpose({
  clearSearch,
});
</script>

I tried using ref assigning to the component, but it didnt worked`


Solution

  • Use a ref:

    const $hero = ref()
    
    //later after mounting
    
    $hero.value.clearSearch()
    
    // in template
    
    <hero ref=”$hero" ..