在 Vue3 中全局禁用属性继承

Disable attribute inheritance globally in Vue3

Vue3 - is there any way to globally disable 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));

技术上可以通过使用 global mixin:

为每个组件设置 inheritAttrs=false
// main.js
import { createApp } from 'vue'

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

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

demo

我们最终编写了一个 vite 插件来避免 mixins(因为我们使用的是 vue3,而 mixins 仅用于 backwards compatibility)自动注入 { inheritAttrs: false }:

import { Plugin } from 'vite';

const DISABLED_INHERIT_SCRIPT = `
  <script lang="ts"> 
    export default { inheritAttrs: false }; 
  </script>
`;

export const disableAttributeInheritance = (disable = true): Plugin => ({
  name: 'DisableInheritAttributesPlugin',
  transform: (src, id) => ({
    code:
      id.endsWith('.vue') && disable
        ? `${src}\n\n${DISABLED_INHERIT_SCRIPT}`
        : src,
    map: null
  })
});

并像这样使用它:

export default defineConfig({
  plugins: [
    disableAttributeInheritance(),
    vue()
  ]
});