vue中使用标签的ref属性

205 阅读1分钟

标签的ref属性

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

ref用在普通的DOM标签上,获取的是DOM节点

ref用在组件标签上,获取的是组件实例对象(如果组件需要使用ref中的值,需要使用defineExpose导出需要使用的属性)

<script lang="ts" setup>
import TagRef from '@/components/TagRef.vue'
import { ref } from 'vue'

// 创建一个title,用于存储ref标记的内容(即使创建一个容器)
//为什么在DOM中使用ref标签,而不使用id区分,是因为id避免id相同冲突
const title = ref()

const person = ref()

/**获取html中标签ref的内容*/
const getRefDomValue = () => {
  console.log(title.value)
}

/**获取自定义组件中标签ref的内容*/
const getRefComponentValue = () => {
  console.log(person.value)
}
</script>

<template>
  <div>
    <div class="person">
      <h1>viteDemo</h1>
      <h2 ref="title">标签内容</h2>
      <button @click="getRefDomValue">获取组件ref中的某些值</button>
      <button @click="getRefComponentValue">获取组件ref中的某些值</button>
    </div>
    <TagRef ref="person" />
  </div>
</template>
<style scoped>
button {
  margin: 10px 10px;
}
</style>
<script setup lang="ts">
import { ref } from 'vue'

const name = ref('张三')

const age = ref(18)

const title = ref()

const showH2 = () => {
  console.log(title.value)
}

//这是暴露在组件上使用ref标签,可以访问到的值,没有暴露的就访问不到
defineExpose({ name, age })
</script>

<template>
  <div class="person">
    <h1>中国</h1>
    <h2 ref="title">北京</h2>
    <h3>有道</h3>
    <button @click="showH2">输出H2这个元素</button>
  </div>
</template>
<style scoped>
.person {
  background-color: skyblue;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}
</style>

顺便说一下标签中的scoped,类似定义按钮的样式使用scoped就会打印如下,开发中默认都要加上scoped

image.png

如果不加scoped就会打印如下

image.png