vue3 + ts(typescript) ref 獲取單個/多個dom元素


個人網站
https://kuangyx.cn
template

<input type="text" ref="inputRef" />
<!-- 加冒號傳入divs方法 -->
<div v-for="i of 3" :key="i" :ref="divs"></div>

setup

// 獲取單個dom
const inputRef = ref<HTMLElement | null>(null);

// 獲取多個dom
const arr = ref([]);
const divs = (el: HTMLElement) => {
  // 斷言為HTMLElement類型的數組
  (arr.value as Array<HTMLElement>).push(el);
  
  // 這樣寫編譯器會拋出錯誤 
  // --> Argument of type 'HTMLElement' is not assignable to parameter of type 'never'.
  // arr.value.push(el);
};
onMounted(() => {
  // 加載完成獲取input焦點
  inputRef.value && inputRef.value.focus();
  // 打印多個ref DOM
  console.log(arr);
});
return {
  inputRef,
  divs,
};


免責聲明!

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



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