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

選項 API Hook 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM