ref标签、style的scope

ref标签

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

  • 用在普通DOM标签上,获取的是DOM节点。
  • 用在组件标签上,获取的是组件实例对象。

DOM:

vue 复制代码
<template>
  <div class="person">
    <h2 ref="title2">上海</h2>
    <button @click="showTitle2">显示title2</button>
  </div>
</template>

<script lang="ts" setup name="Person">
import { ref, onMounted } from 'vue'
// 创建一个title2的ref
let title2 = ref();

function showTitle2() {
  console.log(title2.value);
}
</script>

组件:

父组件:

vue 复制代码
<template>
  <div id="app">
    <h2 ref="title2">北京</h2>
    <button @click="showTitle2">显示title2</button>
    <Person ref="psn" />
  </div>
</template>

<script lagn="ts" setup>
  import Person from './components/Person.vue';
  import { ref, onMounted } from 'vue';
  // 创建一个title2的ref
  let title2 = ref();
  let psn = ref();
  
  function showTitle2() {
    console.log(title2.value);
  }
</script>

<style scoped>
  .app {
    background-color: aqua;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
  }
</style>

子组件:

需要将想让父组件查看的ref标签导出

使用:defineExpose

vue 复制代码
<template>
  <div class="person">
    <h2 ref="title2">上海</h2>
    <button @click="showTitle2">显示title2</button>
  </div>
</template>

<script lang="ts" setup name="Person">
import { ref, onMounted } from 'vue'
// 创建一个title2的ref
let title2 = ref();

function showTitle2() {
  console.log(title2.value);
}

defineExpose({
  title2
})
</script>

style的scoped

组件中<style>添加scoped属性表示:只有当前组件对应得模板<templete>内的可以使用,其他组件不能使用。

vue 复制代码
<template>
  <div id="app">
    <h2 ref="title2">北京</h2>
    <button @click="showTitle2">显示title2</button>
    <Person ref="psn" />
  </div>
</template>

<script lagn="ts" setup>
  import Person from './components/Person.vue';
  import { ref, onMounted } from 'vue';
  // 创建一个title2的ref
  let title2 = ref();
  let psn = ref();
  
  function showTitle2() {
    console.log(title2.value);
  }
</script>

<style scoped>
  .app {
    background-color: aqua;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
  }
</style>
相关推荐
崔庆才丨静觅31 分钟前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60611 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅2 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅3 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊3 小时前
jwt介绍
前端
爱敲代码的小鱼3 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax