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>
相关推荐
li35745 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj5 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel6 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel6 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
^Rocky7 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
西陵7 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld7 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
笑鸿的学习笔记7 小时前
JavaScript笔记之JS 和 HTML5 的关系
javascript·笔记·html5
东风西巷9 小时前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求