VUE 标签的ref属性

在 Vue.js 中,ref 是一个特殊的属性,它允许我们为元素或子组件注册一个引用信息。引用信息将会注册在父组件的 $refs 对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例。

1.普通DOM上使用

<template>
    <div>
        <h2 ref="title">HelloWorld</h2>
        <button @click="print">打印</button>
    </div>
</template>
<script lang="ts" setup>
    import {ref} from 'vue'
    let title = ref()
    
    function print(){
        console.log(title.value)
    }
</script>

 2.子组件上使用

// HelloWorld.vue
<template>
    <div>
        <h2 ref="title">HelloWorld</h2>
        <button @click="print">打印</button>
    </div>
</template>
<script lang="ts" setup>
    import {ref, defineExpose} from 'vue'
    let title = ref()
    
    function print(){
        console.log(title.value)
    }
    let a = ref(1)
    // 暴露给父组件,父组件才可以使用
    defineExpose({a})
</script>
// App.vue
<template>
  <HelloWorld ref="child"/>
  <button @click="fatherPrint">父组件打印</button>
</template>

<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue';
import { ref } from 'vue';
let child = ref();
function fatherPrint() {
  console.log('fatherPrint', child.value);
  console.log('child.a', child.value.a);
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值