Search code examples
vuejs3ref

how to replace this.$refs in composition API


How to replace this.$refs in composition API. I have PostComponent:

<script setup>
import CreateComponent from "./CreateComponent.vue";
import IndexComponent from "./IndexComponent.vue";
</script>
<template>
    <div >
        <create-component />
        <index-component ref="index"  />
    </div>
</template>
<style scoped>
</style>

and IndexComponent:

<script setup>
    const indexLog = () => {
        console.log('this is index component');
    }
    </script>
    <template>
        <div >
                <h1> Bla Bla <h1>
        </div>
    </template>

in option API when I want to get text from IndexComponent indexLog function it is simple I wrote this.$refs.index.indexLog() in PostComponent mounted:

mounted(){
    console.log(this.$refs.index.indexLog())
} 

and I got this in console:

this is index component

but how to get the same functionality with vuejs 3 and script setup?


Solution

  • You just use ref on that child component. Here's the example:

    
    <script setup>
    import CreateComponent from "./CreateComponent.vue";
    import IndexComponent from "./IndexComponent.vue";
    import { ref, onMounted } from 'vue'
    
    const child = ref(null)
    
    onMounted(() => {
      // child.value will hold an instance of <Child />
      console.log(child.value.indexLog())
    })
    </script>
    <template>
        <div >
            <create-component />
            <index-component ref="child"  />
        </div>
    </template>
    <style scoped>
    </style>
    

    In the child component, you have to expose the value that you want to give the parent access to, like this:

    <script setup>
        const indexLog = () => {
            console.log('this is index component');
        }
       // Compiler macros, such as defineExpose, don't need to be imported
       defineExpose({
         indexLog
       })
        </script>
        <template>
            <div >
                    <h1> Bla Bla <h1>
            </div>
        </template>
    

    You can check out the official vue docs for referencing child component here