【问题标题】:Use plugin given Vue constructor for component inheritance with vue-component-class使用给定 Vue 构造函数的插件与 vue-component-class 进行组件继承
【发布时间】:2023-03-24 20:13:01
【问题描述】:

我有一个创建多个全局可用组件的插件,这些组件访问由主应用程序中其他插件设置的实例属性。在大多数 Typescript 示例中,人们通过 import { Vue } from 'vue'import { Vue } from 'vue-property-decorator' 获取他们的 Vue 构造函数,但是我想使用传递给我的插件的 vue 构造函数。你会怎么做?

这是我的尝试,可悲的是没有奏效。我知道它可以在不使用类的情况下工作,但这不是重点。

// app/main.ts

import Vue from 'vue';
import Vuetify from 'vuetify';
import { MyComponentsPlugin } from 'my-components-plugin';

import App from './App';

Vue.use(Vuetify);
Vue.use(MyComponentsPlugin);

new Vue({
  render: h => h(App)
});
// my-components-plugin/main.ts

import { VueConstructor } from 'vue';

import MyComponentExport from './components/MyComponent/Component.vue';

export async function MyComponentsPlugin(
  vue: VueConstructor,
  options?: any,
): Promise<void> {
  vue.component('MyComponent', MyComponentExport(vue));
}
// my-components-plugin/components/Component.vue

<template>
  <p>toto</p>
</template>

<script lang="ts">
import { VueConstructor } from 'vue';
import { Component, Prop } from 'vue-property-decorator';

export default function(Vue: VueConstructor) {
 @Component
  class Header extends Vue {
    private mounted() {
      console.log(this.$vuetify);
    }
  }

  return Header;
}
</script>

<style></style>

【问题讨论】:

  • 乔纳斯你找到答案了吗?
  • 是的,我会发布答案。

标签: typescript inheritance vue.js vuejs2 vue-class-components


【解决方案1】:

要解决此问题,您需要在您的 vue.config.js 中更新您的 webpack 配置。添加:

const path = require('path');

module.exports = {
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'development') {
      config.resolve.modules.prepend(path.resolve(__dirname, './node_modules'));
    }
  },
};

这样,您的项目依赖项将首先搜索您的项目本地 node_modules 以找到它们的依赖项,因此它们将使用与主应用程序相同的 Vue

我们不需要为生产环境添加它,因为捆绑包将被优化并防止Vue代码重复。

【讨论】:

    猜你喜欢
    • 2016-10-30
    • 2021-07-03
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2018-11-06
    • 2023-02-06
    • 2018-11-12
    • 2019-09-24
    相关资源
    最近更新 更多