This is the third day of my participation in the Novembermore Challenge

How do I get child components or byte points in SETUP () of VUe3? How do you implement something like $refs?

For example, 🌰, want to achieve the effect that the input field automatically gets focus after rendering

Template:

<template> <div class="container"> <el-input v-model="inputValue" ref="inputRef" @input="inputChange" Placeholder =" input "></el-input> </div> </template>Copy the code

Effect:

Way 1. Ref ()

A similar function to $refs can be achieved through the ref() function

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
    }
  }
})
Copy the code

Way 2. GetCurrentInstance ()

GetCurrentInstance allows access to internal component instances that are useful to advanced usage or library creators. — Introduction to official documents

So you can use this method to achieve the effect of 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
    }
  }
})
Copy the code

The official documentation explicitly states that getCurrentInstance uses restricted links

\