vue3学习笔记之$refs

5,360 阅读1分钟

这是我参与11月更文挑战的第3天,活动详情查看:11月更文挑战

在vue3 的setup()中如何拿到子组件或字节点?如何实现类似$refs的功能?

举个栗子🌰, 想实现渲染完成后input输入框自动获焦点的效果

模版:

<template>
  <div class="container">
    <el-input v-model="inputValue" ref="inputRef" @input="inputChange" placeholder="请输入内容"></el-input>
  </div>
</template>

效果图: image

方式1.ref()

通过ref()函数可以实现类似$refs功能

import { ref, defineComponent, onMounted } from "vue";
export default defineComponent({
  setup () {
    const inputRef = ref();
    onMounted(() => {
      inputRef.value.focus();
    });
    const inputChange = v => {
      console.log(v);
    }
    return {
      inputValue: ref(""),
      inputRef,
      inputChange
    }
  }
})

方式2.getCurrentInstance()

getCurrentInstance 允许访问对高级用法或库创建者有用的内部组件实例。 --官方文档介绍

所以可以使用该方法实现 this的效果

import { ref, defineComponent, onMounted, getCurrentInstance } from "vue";
export default defineComponent({
  name: "Home",
  setup () {
    const internalInstance = getCurrentInstance();
    onMounted(() => {
      internalInstance.ctx.$refs.inputRef.focus();
    });
    const inputChange = v => {
      console.log(v);
    }
    return {
      inputValue: ref(""),
      inputChange
    }
  }
})

tip: 官方文档中明确说明getCurrentInstance使用限制链接

\