SoFunction
Updated on 2025-04-04

How to operate components using ref tags in Vue3

Vue3 uses ref tags

In Vue2, this.$ is generally used to obtain component objects.
This method is not used in Vue3
For example:

 <el-upload class="upload-demo" action="" :http-request="handleUpload" 
                    :on-change="handleChange"
          :before-upload="handleBeforeUpload" :show-file-list="false" :auto-upload="false" :limit="1" ref="uploadRef">
          <el-button type="primary" icon="upload" slot="trigger">Import</el-button>
        </el-upload>

Want to get the el-upload component object

Create first

const uploadRef =  ref()

If you use it, you need to
For example:

 // Clear the upload list  ()

Supplement: Use the ref tag component in Vue3

In Vue3, we can also use ref to mark components to obtain properties and methods of parent and child components.

Parent component

<template>
<hello-world ref='son'></hello-world>
&lt;button @click='getSon()'>Get</button>
 </template>

 <script setup>
 // First, introduce subcomponents firsttimport HelloWorld from './components/'

// Then introduce ref and declare sonimport {ref} from 'vue'
const son = ref()
const getSon = () =&gt; {
()
()
}

&lt;/script&gt;

Subcomponents

&lt;template&gt;
  &lt;div&gt; {{ title }} &lt;/div&gt;
&lt;/template&gt;

&lt;script setup&gt;
import {ref} from 'vue'
const title = ref('I'm the title of the child component')
const sonMethod = () =&gt; {
  ('I'm a method for child components')
}

// The most important step is that we need to expose the properties and methods required by the parent component so that the parent component can obtaindefineExpose({sonMethod, title})
&lt;/script&gt;

This article about how to use the ref tag in Vue3 and operate components is introduced here. For more information about Vue3 using the ref tag, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!