前端学习-vue视频学习007-标签的ref属性
给标签增加ref属性,可以通过属性值取到标签内容
<template>
<div class="person">
<h1>this</h1>
<h2 ref="title">that</h2>
<button @click="showLog">changeTemp</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,watch,watchEffect} from 'vue'
let title = ref()
function showLog(){
console.log(title.value);
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin : 0 5px;
}
li {
font-size : 20px;
}
</style>
data-v-xxxx 局部标识
如果在style中加了scoped,代表为局部样式,使用ref标签时会出现data-v-xxxx 标识
<style scoped>
</style>
在组件标签中使用ref标签
如果根组件想要获取components文件内的数据,需要两步:
- 在根组件内的组件标签内增加ref标签
- 对应组件文档中使用defineExpose
App.vue
<template>
<Person ref="temp"/>
<button @click="showLog">test</button>
</template>
<script lang="ts" setup name="App">
import Person from './components/Person.vue';
import {ref} from 'vue'
let temp = ref()
// 如果components的文件内不使用defineExpose,是无法获取到组件标签内的数据的
function showLog(){
console.log(temp.value);
}
</script>
Person.vue
<template>
<div class="person">
<h1>this</h1>
<h2 ref="title">that</h2>
<button @click="showLog">changeTemp</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,defineExpose} from 'vue'
let title = ref()
let a = ref(0)
let b = ref(1)
let c = ref(2)
function showLog(){
console.log(title.value);
}
// 将数据a,b暴露给根组件,隐藏c
defineExpose({a,b})
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin : 0 5px;
}
li {
font-size : 20px;
}
</style>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!