Vue3【十五】标签的Ref属性

Vue3【十五】标签的Ref属性

标签的ref属性 用于注册模板引用

用在dom标签上,获取的是dom节点

用在组件上,获取的是组件实例对象

案例截图

目录结构

代码

app.vue

html 复制代码
<template>
    <div class="app">
        <h1 ref="title2">你好世界! 我是App根组件</h1>
        <button @click="showLog">点我输出h1标签></button>
        <Person ref="rrr" />
    </div>
</template>

<script lang="ts" setup name="App">
import Person from './components/Person.vue'
import { ref } from 'vue'

let title2 = ref()
let rrr = ref()

function showLog() {
    console.log(title2.value)
    console.log(rrr.value)
}

// export default {
//     name: 'App', //组件名字
//     // 注册组件
//     components: {
//         Person
//     }
// }

</script>

<style>
.app {
    background-color: #4fffbb;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px;
}
</style>

person.vue

html 复制代码
<template>
    <div class="person">

        <h1>标签ref属性</h1>
        <h2 ref="title2">需求:转速大于2000时候换挡位,不能超过D6挡位</h2>
        <h2>转速</h2>
        <button @click="showLog">点击输出 ref = title2 的元素</button>

    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';

// 标签的ref属性 用于注册模板引用
// 用在dom标签上,获取的是dom节点
// 用在组件上,获取的是组件实例对象

// 创建一个title2的ref,用于存储ref标记的内容
const title2 = ref();
let a = ref(0);
let b = ref(1);
let c = ref(2);
function showLog() {
    console.log(title2.value);
}

// 将ref对象暴漏给父组件
defineExpose({ a, b, c });

</script>

<style scoped>
.person {
    background-color: #ff9e4f;
    box-shadow: 0 0 10px;
    border-radius: 30px;
    padding: 30px;
}

button {
    margin: 0 10px;
    padding: 0 5px;
    box-shadow: 0 0 5px;
    ;
}
</style>
相关推荐
中微子4 小时前
🔥 React Context 面试必考!从源码到实战的完整攻略 | 99%的人都不知道的性能陷阱
前端·react.js
秋田君4 小时前
深入理解JavaScript设计模式之命令模式
javascript·设计模式·命令模式
中微子5 小时前
React 状态管理 源码深度解析
前端·react.js
风吹落叶花飘荡6 小时前
2025 Next.js项目提前编译并在服务器
服务器·开发语言·javascript
加减法原则6 小时前
Vue3 组合式函数:让你的代码复用如丝般顺滑
前端·vue.js
yanlele7 小时前
我用爬虫抓取了 25 年 6 月掘金热门面试文章
前端·javascript·面试
lichenyang4537 小时前
React移动端开发项目优化
前端·react.js·前端框架
天若有情6737 小时前
React、Vue、Angular的性能优化与源码解析概述
vue.js·react.js·angular.js
你的人类朋友7 小时前
🍃Kubernetes(k8s)核心概念一览
前端·后端·自动化运维
web_Hsir7 小时前
vue3.2 前端动态分页算法
前端·算法