Refs模板
Refs 模板用来获取页面 DOM 元素或者组件,类似于 Vue2.X 中的 $refs。
Refs 模板的使用方法如下。
(1)在 setup() 中创建 ref 对象,其值为 null。 (2)为元素添加 ref 属性,其值为步骤(1)中创建的 ref 对象名。 (3)完成页面渲染之后,获取 DOM 元素或者组件。
创建新组件 ComRefDom.vue,代码如下。
<template>
<div>
// 2.为元素添加 ref 属性,其值为 ref 返回的对象
<h1 ref="msg">Hello Vue3</h1>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
setup() {
// 1.使用 ref 函数定义响应式数据,传入 null
var msg = ref(null);
// 3.完成页面渲染之后使用 DOM 元素
onMounted(() => {
console.log(msg.value);
msg.value.style.color = 'red';
});
return {
msg,
};
},
};
</script>
代码解析如下。
上述代码中,msg.value 获取到的就是 h1 标签。
使用 Refs 模板获取组件:创建 ComRef 组件,代码如下。
<template>
<div>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
import { ref } from "vue";
export default {
setup() {
var msg = ref("Hello Refs");
var btn = () => {
console.log(msg.value);
};
return {
msg,
btn,
};
},
};
</script>
新建父组件,在组件中引用 ComRef 子组件。
<template>
<div>
// 2.为组件添加 ref 属性,其值为 ref 返回的对象
<ComRef ref="Commsg"></ComRef>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
import ComRef from '../components/ComRef.vue'; // 确保路径正确
export default {
setup() {
// 1.使用 ref 函数定义响应式数据,传入 null
var Commsg = ref(null);
// 3.完成页面渲染之后,使用组件中的属性或者方法
onMounted(() => {
// 确保 Commsg.value 存在,因为组件可能是异步加载的
if (Commsg.value) {
// 调用子组件中的数据
console.log(Commsg.value.msg);
// 调用子组件中的方法
Commsg.value.btn();
} else {
console.log("ComRef 组件尚未加载完成");
}
});
return {
Commsg,
};
},
components: {
ComRef,
},
};
</script>
代码解析如下。
此时通过 ref,可以在父组件中直接调用子组件中的数据和方法。