从“追求尽量不出错”,到正视“出错是必然”的转变,才是微|

如此而已~~~

园龄:3年3个月粉丝:0关注:12

标签的ref属性

标签的ref属性

参考文档:https://cn.vuejs.org/api/built-in-special-attributes.html#ref

作用:用于注册模板引用。

​ 用在普通DOM标签上,获取的是DOM节点。因为通过id获取不同组件的对应DOM标签会出现问题,本质上vue是挂载到跟组件的单页面,如果使用id属性获取,比如在父子组件中都用id="xxx",那么在子组件中通过id获取的就是父组件先加载的或者其他情况。

​ 用在组件标签上,获取的是组件实例对象。

用在普通DOM标签上:

<template>
<div class="person">
<h1 ref="title1">尚硅谷</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()
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)
}
</script>

用在组件标签上:

<!-- 父组件App.vue -->
<template>
<Person ref="ren"/>
<button @click="test">测试</button>
</template>
<script lang="ts" setup name="App">
import Person from './components/Person.vue'
import {ref} from 'vue'
let ren = ref()
function test(){
console.log(ren.value.name)
console.log(ren.value.age)
}
</script>
<!-- 子组件Person.vue中要使用defineExpose暴露内容 -->
<script lang="ts" setup name="Person">
import {ref,defineExpose} from 'vue'
// 数据
let name = ref('张三')
let age = ref(18)
/****************************/
/****************************/
// 使用defineExpose将组件中的数据交给外部
defineExpose({name,age})
</script>

本文作者:如此而已~~~

本文链接:https://www.cnblogs.com/fragmentary/p/18626685

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   如此而已~~~  阅读(32)  评论(0编辑  收藏  举报
//雪花飘落效果
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起