目录
1. ref 的作用
2. 如何使用
1. ref 的作用
用于注册模板引用
用在普通DOM标签上,获取的是DOM节点。
用在组件标签上,获取的是组件的实例对象。
2. 如何使用
代码如下
<template><div class="app"><h2 ref="title">你好呀</h2><button @click="test">测试</button><Person ref="person"></Person></div>
</template><script setup lang="ts">
import Person from './components/Person.vue'
import { ref } from 'vue';let title = ref();
let person = ref();
function test() {console.log(title.value)console.log(person.value)
}
</script><style>
.app{background: wheat;padding: 20px;
}
</style>
值得一提的是,这里的获取的组件的实例对象是没有任何信息的。如果想拿到子组件中的信息,需要在子组件 Person.vue 中要使用 defineExpose 暴露内容。
代码如下
<template><div class="person"><div class="person"><h1>需求:水温达到50℃,或水位达到20cm,则联系服务器</h1><h2 id="demo">水温:{{ temp }}</h2><h2>水位:{{ height }}</h2><button @click="changePrice">水温+1</button><button @click="changeSum">水位+10</button></div></div>
</template><script lang="ts" setup name="Person">import {ref,watch,watchEffect} from 'vue'// 数据let temp = ref(0)let height = ref(0)// 方法function changePrice(){temp.value += 10}function changeSum(){height.value += 1}watchEffect(()=>{if(temp.value >= 50 || height.value >= 20){console.log('联系服务器')}})defineExpose({temp,height })
</script>
这样控制台打印的内容包含了子组件暴露的内容。