Refs模板用来获取页面DOM元素或者组件,类似于Vue2.X中的$refs。Refs模板的使用方法如下。
(1)在setup()中创建ref对象,其值为null。
(2)为元素添加ref属性,其值为步骤(1)中创建的ref对象名。
(3)完成页面渲染之后,获取DOM元素或者组件。
src\views\HomeView.vue
<template> <div class="home"> <h1 ref="msg2">Hello Vue3</h1> <ComRef ref="msg3"></ComRef> </div> </template> <script setup> import HelloWorld from '@/components/HelloWorld.vue' import ComRef from '@/components/ComRef.vue' import {ref, onMounted} from 'vue' var msg2 = ref(null); var msg3 = ref(null); onMounted(() => { console.log(msg2.value) // msg2.value获取到的就是h1标签 msg2.value.style.color = 'grey' console.log(msg3.value) console.log(msg3.value.msg) msg3.value.btn() }) </script>
src\components\ComRef.vue
<template> <span> <p>ComRef.vue: {{msg}}</p> </span> </template> <script setup> import {ref} from "vue" var msg = ref("Hello Refs") var btn = () => { console.log("btn:" + msg.value) } defineExpose({ msg, btn }) </script>
标签:vue,Refs,value,Vue3,msg,btn,ref,模板 From: https://www.cnblogs.com/ooo0/p/17664353.html