Vue3: ref 拿到 DOM / 组件实例

获得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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值