优秀的编程知识分享平台

网站首页 > 技术文章 正文

vue3通过ref获取元素

nanyue 2025-01-06 14:39:20 技术文章 4 ℃

利用ref函数获取组件中的标签元素,可以操作该标签身上的属性,还可以通过ref来取到子组件的数据,可以修改子组件的数据、调用子组件的方法等、非常方便. 适用于vue3.0版本语法,后续会讲到vue3.2版本setup语法糖有所不同。

语法示例:

<input标签 type="text" ref="inputRef">

<子组件 ref="childRef" />

const inputRef = ref<HTMLElement|null>(null)

const childRef = ref<HTMLElement|null>(null)

父组件代码:

<template>
  <div style="font-size: 14px;">
    <h2>测试ref获取普通标签 让输入框自动获取焦点</h2>
    <input type="text" ref="inputRef">

    <h2>测试ref获取子组件</h2>
    <Child ref="childRef" />
  </div>
</template>

<script lang="ts">
// vue3.0版本语法
import { defineComponent, ref, onMounted } from 'vue'
import Child from './child.vue'
export default defineComponent({
  components: {
    Child
  },
  setup() {
    const inputRef = ref<HTMLElement|null>(null)
    const childRef = ref<HTMLElement|null>(null)
      
    onMounted(() => {
      // ref获取元素: 利用ref函数获取组件中的标签元素
      // 需求实现1: 让输入框自动获取焦点
      inputRef.value && inputRef.value.focus()
      // ref获取元素: 利用ref函数获取组件中的标签元素
      // 需求实现2: 查看子组件的数据,修改子组件的某个值
      console.log(childRef.value);
      setTimeout(() => {
        childRef.value.text = '3秒后修改子组件的text值'
      }, 3000)
    })

    return {
      inputRef,childRef
    }
  },
})
</script>

子组件代码:

<template>
  <div>
    <h3>{{ text }}</h3>
  </div>
</template>

<script lang="ts">
// vue3.0版本语法
import { ref, defineComponent } from "vue";

export default defineComponent({
  name: "Child",
  setup() {
    const text = ref('我是子组件');

    return {
      text
    };
  },
});
</script>

初始页面效果-输入框获取到了焦点,log打印出了子组件的所有数据:

初始3秒后页面效果,修改了子组件的text数据:

vue3.2版本语法:

<template>
  <div style="font-size: 14px;">
    <h2>测试ref获取普通标签 让输入框自动获取焦点</h2>
    <input type="text" ref="inputRef">

    <h2>测试ref获取子组件</h2>
    <Child ref="childRef" />
  </div>
</template>

<script lang="ts" setup>
// vue3.2版本语法
import {  ref, onMounted } from 'vue'
import Child from './child.vue'
const inputRef = ref<HTMLElement|null>(null)
const childRef = ref<HTMLElement|null>(null) 
onMounted(() => {
  // ref获取元素: 利用ref函数获取组件中的标签元素
  // 需求实现1: 让输入框自动获取焦点
  inputRef.value && inputRef.value.focus()
  // ref获取元素: 利用ref函数获取组件中的标签元素
  // 需求实现2: 查看子组件的数据,修改子组件的某个值
  console.log(childRef.value);
  setTimeout(() => {
    childRef.value.text = '3秒后修改子组件的text值'
  }, 3000)
})
</script>
最近发表
标签列表