关于javascript:vue3-tstypescript-ref-获取单个多个dom元素

10次阅读

共计 506 个字符,预计需要花费 2 分钟才能阅读完成。

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,
};
正文完
 0