Vue3使用ref标签

在Vue2中 一般用 this.$ref.xxxx 进行获取组件对象
Vue3中就不使用这个方法了
例如:

 <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">导入</el-button>
        </el-upload>

想要获取el-upload组件对象

先创建

const uploadRef =  ref()

使用的话需要xxx.value.xxx
例如:

 // 清除上传列表
  uploadRef.value.clearFiles()

补充:Vue3 中 ref 标记组件使用

在 Vue3 中我们还可以使用 ref 标记组件来进行获取父子组件获取属性和方法的操作。

父组件

<template>
<hello-world ref='son'></hello-world>
<button @click='getSon()'>获取</button>
</template>

<script setup>
// 首先还是先引入子组件
import HelloWorld from './components/HelloWorld.vue'

// 然后引入 ref ,并声明 son
import {ref} from 'vue'
const son = ref()
const getSon = () => {
console.log(son.value.title)
son.value.sonMethod()
}

</script>

子组件

<template>
  <div> {{ title }} </div>
</template>

<script setup>
import {ref} from 'vue'
const title = ref('我是子组件的title')
const sonMethod = () => {
  console.log('我是子组件的方法')
}

// 最要的一步,这里我们需要把父组件需要的属性和方法暴露出去,这样父组件才能获取的到
defineExpose({sonMethod, title})
</script>