您的位置:首页 > 游戏 > 手游 > Vue3: ref 拿到 DOM / 组件实例

Vue3: ref 拿到 DOM / 组件实例

2024/10/5 14:19:24 来源:https://blog.csdn.net/weixin_52268321/article/details/141038011  浏览:    关键词:Vue3: ref 拿到 DOM / 组件实例

获得DOM

<script setup>
import { onMounted, ref } from "vue";
// #1
const dom = ref(null);
onMounted(() => {// #3console.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(() => {// #4console.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)// #3testRef.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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com