获得DOM
<script setup>
import { onMounted, ref } from "vue";
// #1
const dom = ref(null);
onMounted(() => {
// #3
console.log(dom.value);
});
</script>
<template>
<!-- #2 -->
<div ref="dom">我是box</div>
</template>
配合 v-for 循环获取一组 DOM
<script setup>
import { onMounted } from "vue";
// #1
const domList = [];
// #2
const setDom = (el) => {
domList.push(el);
};
onMounted(() => {
// #4
console.log(domList);
});
</script>
<template>
<ul>
<!-- #3 -->
<li v-for="i in 4" :key="i" :ref="setDom">第 {{ i }} li</li>
</ul>
</template>
获取组件实例
获取组件实例的目的一般是操作组件内部的属性或方法
App.vue
<script setup>
import { ref } from 'vue';
import Test from './Test.vue'
// ref 函数配合 ref 属性可以获取组件实例,获取组件实例的目的一般是操作组件内部的属性或方法
// #1
const testRef = ref(null)
const updateTestData = () => {
// 一旦拿到组件实例,就可以使用组件内部所有的属性和方法
// console.log(testRef.value)
// #3
testRef.value.changeNum(3)
}
</script>
<template>
<!-- #2 -->
<Test ref="testRef"/>
<button @click="updateTestData">在父组件修改 Test 组件的数据</button>
</template>
Test.vue
<script setup>
import { ref } from "vue";
const num = ref(1)
const changeNum = (step = 1) => {
num.value += step
}
// #4 script setup 内部的变量/函数对外是封闭的 使用defineExpose导出变量和函数
defineExpose({
num,
changeNum
})
</script>
<template>
<div>
{{ num }}
<button @click="changeNum()">+1</button>
</div>
</template>
<style scoped></style>