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>
相关推荐
西西学代码1 分钟前
Flutter---DragTarget(颜色拖拽选择器)
前端·javascript·flutter
小光学长1 分钟前
基于Vue的地铁综合服务管理系统7949eg04(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库·vue.js
nihao5619 分钟前
Figma-Context-MCP 帮助前端快速生成页面
前端·ai编程·figma
阿蓝灬34 分钟前
React中的stopPropagation和preventDefault
前端·javascript·react.js
天天向上102436 分钟前
vue3 抽取el-dialog子组件
前端·javascript·vue.js
lecepin41 分钟前
AI Coding 资讯 2025-11-05
前端·javascript
excel44 分钟前
Vue 模板解析器 parserOptions 深度解析
前端
前端小咸鱼一条1 小时前
17.React获取DOM的方式
前端·javascript·react.js
excel1 小时前
Vue 编译核心中的运行时辅助函数注册机制详解
前端
excel1 小时前
🌿 深度解析 Vue DOM 编译器模块源码:compile 与 parse 的构建逻辑
前端