目錄
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>
這樣控制臺打印的內容包含了子組件暴露的內容。