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>
相关推荐
阿諪諪11 分钟前
Vue知识点(5)-- 动画
前端·vue.js·nginx
工会代表16 分钟前
macOS 内外网共存方案:配置双网卡实现网络分流
前端·网络协议·macos
蘑菇头爱平底锅17 分钟前
数字孪生-DTS-孪创城市-项目初始化
前端·数据可视化
陈随易18 分钟前
Bun v1.2.9发布了,内置了Redis操作
前端·后端·程序员
Gazer_S19 分钟前
【lodash的omit函数详解 - 从入门到精通】
javascript·状态模式
DarkLONGLOVE21 分钟前
解锁 JavaScript 技能:全面掌握自定义属性的奥秘
前端·javascript
Aphasia31122 分钟前
CSS 居中方法大全📖
前端·css·面试
顾洋洋23 分钟前
WASM与OPFS组合技系列一(文件导入)
前端·javascript·webassembly
面向大佬编程23 分钟前
vue实现导出excel多层表头
前端
不会笑的卡哇伊25 分钟前
上传没你想得那么难?切片?断点续传?秒传?🎯
前端