『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』 专栏,持续更新中
『未完待续』


相关推荐
~无忧花开~1 天前
JavaScript实现PDF本地预览技巧
开发语言·前端·javascript
一 乐1 天前
宠物管理|宠物共享|基于Java+vue的宠物共享管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·springboot·宠物
小时前端1 天前
“能说说事件循环吗?”—— 我从候选人回答中看到的浏览器与Node.js核心差异
前端·面试·浏览器
IT_陈寒1 天前
Vite 5.0实战:10个你可能不知道的性能优化技巧与插件生态深度解析
前端·人工智能·后端
SAP庖丁解码1 天前
【SAP Web Dispatcher负载均衡】
运维·前端·负载均衡
weixin79893765432...1 天前
Electron + Vue 3 + Vite 实践
vue.js·electron·vite
天蓝色的鱼鱼1 天前
Ant Design 6.0 正式发布:前端开发者的福音与革新
前端·react.js·ant design
HIT_Weston1 天前
38、【Ubuntu】【远程开发】拉出内网 Web 服务:构建静态网页(一)
linux·前端·ubuntu
零一科技1 天前
Vue3拓展:自定义权限指令
前端·vue.js
t***D2641 天前
Vue虚拟现实开发
javascript·vue.js·vr