本示例基于vue3
注意:
<script setup> setup函数是处于生命周期函数beforeCreate之前的函数 ,此时dom还未挂载,直接打印 unref(domH2) 的话是 undefined,所以请在 nextTick() 或 onMounted() 中操作dom元素。
ref绑定单个dom元素
<template>
<div class="slot">
<h2 ref="domH2">父组件</h2>
</div>
</template>
<script setup>
import { ref,unref,onMounted,nextTick } from 'vue';
const domH2 = ref(null);
nextTick(()=>{
console.log(unref(domH2).innerHTML);
// 父组件
})
<script>
ref动态绑定多个dom元素
<template>
<div class="slot">
<h2 ref="domH2" v-for="item in 5">父组件</h2>
</div>
</template>
const domH2 = ref(null);
nextTick(()=>{
const domList = unref(domH2);
domList[2].innerHTML='上杉绘梨衣!';
})
此时获取的是一个dom数组
改变数据后