作用:用于注册模板引用。
用在普通
DOM标签上,获取的是DOM节点。用在组件标签上,获取的是组件实例对象。
用在普通DOM标签上:
<template>
<div class="person">
<h1 id ="title1" ref="title1">vue 学习</h1>
<h2 ref="title2">前端</h2>
<h3 ref="title3">Vue</h3>
<input type="text" ref="inpt"> <br><br>
<button @click="showLog">点我打印内容</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref} from 'vue'
let title1 = ref()
let title2 = ref()
let title3 = ref()
let inpt = ref()
function showLog(){
// 通过id获取元素
const t1 = document.getElementById('title1')
// 打印内容
console.log((t1 as HTMLElement).innerText)
console.log((<HTMLElement>t1).innerText)
console.log(t1?.innerText)
/************************************/
// 通过ref获取元素
console.log(title1.value)
console.log(title2.value)
console.log(title3.value)
console.log(inpt.value)
}
</script>
用在组件标签上

APP.vue
<template>
<div class="app">
<h1>你好啊!</h1>
<Person ref="ren"/>
<button @click="test"> 点击打印log</button>
</div>
</template>
<script lang="ts">
import Person from './components/Person.vue'
import {ref} from 'vue'
export default {
name:'App', //组件名
components:{Person} //注册组件
}
</script>
<script lang="ts" setup >
let ren = ref()
function test(){
console.log(ren.value.name)
console.log(ren.value.age)
}
</script>
<style>
.app {
background-color: #ddd;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>
Person.vue
<script lang="ts" setup name="Person">
import {ref,defineExpose} from 'vue'
// 数据
let name = ref('张三')
let age = ref(18)
/****************************/
/****************************/
// 使用defineExpose将组件中的数据交给外部
defineExpose({name,age})
</script>
126

被折叠的 条评论
为什么被折叠?



