vue3中通过ref获取元素节点(系列十一)

ref

过去在 Vue2 中,我们采用 ref 来获取标签的信息,用以替代传统 js 中的 DOM 行为。

<template>
  <div ref="box">
    I am div
  </div>
</template>

console.log(this.$refs.box);
 

在 Vue3 的组合 API 中,采取了新的方案来执行对应的 ref 标签属性获取。过去我们采用的是 this.$refs 的方案,现在,要首先创建 ref 对象,然后再将这个 ref 对象创建出来,以实现监听。

<template>
  <div ref="box">
    I am div
  </div>
</template>

<script>
import {  ref } from 'vue';


export default {
  name: 'App',
  setup() {
    let box = ref(null);

    return {box};
  }
}
</script>

首先我们创建了一个 box 的监听对象,然后将这个监听对象暴露出去,从而实现 setup 函数中和 节点box 的绑定。

但由于 setup 函数的执行时间要先于 html 标签的渲染,所以我们不能直接在 setup 函数中初始化 box 标签。

  beforeCreate
  setup
  Created

setup函数在这两个生命周期之间执行
setup() {
  let box = ref(null);
  // 此时的 box 虽然监听 div,但控制台打印的是 null。
  console.log(box.value);
  return {box};
}

如果存在有初始化或类似的操作,需要借用 生命周期函数,而在 setup 中,要寻找生命周期需要用到 on+生命周期 的 api

选项 APIHook inside inside setup
beforeCreate Not needed*
created Not needed*
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered

通常来说,使用的会是 onMounted.

<template>
  <div ref="box">
    I am div
  </div>
</template>

<script>
import { onMounted, ref } from 'vue';


export default {
  name: 'App',
  setup() {
    let box = ref(null);
    console.log(box.value);

    // 由于 template 中的 div 属性 ref 引用了一个对象 box,因此 box 将与这个 div 执行绑定。
    // 但由于 setup 执行时期,还未创建实际的 div,所以如果要进行与 box 的交互,必须在生命周期中间执行获取。
    // onMounted() 中的行为会在声明周期 mounted 中执行。
    onMounted(() => {
      console.log('box.value', box.value);
    })


    return {box};
  }
}
</script>

至此,我们成功获取到了 box 指定的 div 标签。

BF4Q1A.png

原文地址:https://www.cnblogs.com/fsg6/p/14486080.html