前端学习-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>
posted @   ayubene  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示