【问题标题】:Disable attribute inheritance globally in Vue3在 Vue3 中全局禁用属性继承
【发布时间】:2022-01-16 23:22:15
【问题描述】:

Vue3 - 有没有办法全局禁用Attribute Inheritance?我知道在注册/创建新组件时可以将inheritAttrs 设置为false,但是如果我想一般禁止这种行为而不必更改/添加inheritAttrs: false每一个我创建的组件?

一个相关的问题是Vue JS Non prop attributes and Disabling Attribute Inheritance - 但它只是关于是否可能,而不是如何在全球范围内做到这一点......

我想禁用它的原因是我想实现与 React / Angular 中相同的行为 - 在没有收到任何错误 / 警告的情况下转发任何道具会导致不一致 / 意外行为(可能 - 特别是对于诸如class 和其他原生 HTML 属性)。

我们目前的解决方法是导入和重新导出任何组件并“预处理”它们:

import * as components from './components.ts'; // all components are re-exported with names
export * from './components.ts';

// Disable attribute-inheritance for every single component
Object.values(components).forEach((v) => (v.inheritAttrs = false));

【问题讨论】:

  • 我建议不要尝试这样做,因为修改默认全局行为可能会产生长期后果,例如破解第三方组件。如果您想为自己的组件创建此默认行为,请为 defineComponent 创建自定义包装器

标签: vue.js vuejs3


【解决方案1】:

技术上可以使用global mixin为每个组件设置inheritAttrs=false

// main.js
import { createApp } from 'vue'

createApp(App)
  .mixin({ inheritAttrs: false }) ?
  .mount('#app')

但是,您应该注意,这不会导致 Vue 在尝试设置不存在的道具时发出警告/错误。任何此类用法都会被忽略。

demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 2021-12-31
    • 1970-01-01
    • 2017-12-18
    • 2014-02-03
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多