『VUE』27. 透传属性与inheritAttrs(详细图文注释)

目录


欢迎关注 『VUE』 专栏,持续更新中
欢迎关注 『VUE』 专栏,持续更新中

什么是透传属性(Forwarding Attributes)

在 Vue.js 中,透传属性(Forwarding Attributes)是指在组件中将父组件传递给子组件的属性,直接传递给子组件内部的某个特定元素或子组件。这样可以使得父组件的属性在子组件中使用,而无需显式地在子组件中声明这些属性。


使用条件唯一根节点

相当于<h3>透传属性</h3>获得了<AttrComponent class="attr-container" />class="attr-container"

如果有如下结构,有两个h3那么不是唯一的根节点,不会生效

html 复制代码
<template>
  <h3>透传属性</h3>
  <h3>透传属性2</h3>
</template>

App.vue

html 复制代码
<template>
  <!-- <GlobalHeader />
  <Main />
  <Aside /> -->
  <!-- <Parent /> -->
  <!-- <ComponentEvent /> -->
  <!-- <ComponentP /> -->
  <AttrComponent class="attr-container" />
</template>

<script>
// import Header from "./page/Header.vue";
// import Main from "./page/Main.vue";
// import Aside from "./page/Aside.vue";
// import Child from "./components/Child.vue";
// import Parent from "./components/Parent.vue";
// import ComponentEvent from "./components/ComponentEvent.vue";
// import ComponentEventSon from "./components/ComponentEventSon.vue";
// import Main from "./components/Main.vue";
// import ComponentP from "./components/ComponentP.vue";
import AttrComponent from "./components/AttrComponent.vue";

export default {
  components: {
    // Header,
    // Main,
    // Aside,
    // Child,
    // Parent,
    // ComponentEvent,
    // ComponentEventSon,
    // Main,
    // ComponentP,
    AttrComponent,
  },
};
</script>

<style scoped></style>
./components/ComponentP.vue

AttrComponent.vue

html 复制代码
<template>
  <h3>透传属性</h3>
</template>

<style>
.attr-container {
  color: red;
}
</style>

禁用透传属性继承

使用 inheritAttrs: false: 在子组件中将 inheritAttrs 设置为 false,可以阻止自动将父组件的属性应用到根元素上,需要手动处理透传属性。

AttrComponent.vue

html 复制代码
<template>
  <h3>透传属性</h3>
  <!-- <h3>透传属性2</h3> -->
</template>

<script>
export default {
  inheritAttrs: false,
};
</script>

<style>
.attr-container {
  color: red;
}
</style>

总结

大家喜欢的话,给个👍,点个关注!给大家分享更多计算机专业学生的求学之路!

版权声明:

发现你走远了@mzh原创作品,转载必须标注原文链接

Copyright 2024 mzh

Crated:2024-3-1

欢迎关注 『VUE』 专栏,持续更新中
欢迎关注 『VUE』 专栏,持续更新中
『未完待续』


相关推荐
进击的尘埃10 分钟前
GPU 合成层炸了,页面白屏——从 will-change 滥用聊到层爆炸的治理
javascript
葡萄城技术团队10 分钟前
Playwright 官方推荐的 Fixture 模式,为什么大厂架构师却在偷偷弃用?
前端
newbe3652411 分钟前
ImgBin CLI 工具设计:HagiCode 图片资产管理方案
前端·后端
bluceli14 分钟前
CSS Scroll Snap:打造丝滑滚动体验的利器
前端·css
www_stdio15 分钟前
深入理解 React Fiber 与浏览器事件循环:从性能瓶颈到调度机制
前端·react.js·面试
工边页字20 分钟前
LLM 系统设计核心:为什么必须压缩上下文?有哪些工程策略
前端·人工智能·后端
嚣张丶小麦兜28 分钟前
react的理解
前端·react.js·前端框架
重庆穿山甲32 分钟前
身份证照片自动裁剪(OpenCV 四边形检测 + 透视矫正)
前端·后端
跟着珅聪学java32 分钟前
Electron + Vue 现代化“新品展示“和“快捷下单“菜单
开发语言·前端·javascript