【问题标题】:How to use a javascript component in vue.js with typescript?如何在带有打字稿的 vue.js 中使用 javascript 组件?
【发布时间】:2021-06-17 01:26:05
【问题描述】:

我在一个项目中定义了一个组件,想这样公开,以便在另一个项目中使用:

import ToastNotification from '../ToastNotification';
import Api from './api';

const VueToast = (Vue, options = {}) => {
  const methods = Api(Vue, options);
  Vue.$toast = methods;
  Vue.prototype.$toast = methods;
};

ToastNotification.install = VueToast;

export default ToastNotification;

我在 index.js 中声明:

import VueToast from './toast/js/index';

Vue.use(VueToast);

在另一个项目中,我 npm 将此项目安装为库,但 this.$toast('message') 无法识别。它说“类型''上不存在属性'$toast'”

我提到我设法在项目内部使用另一个类'this.$toast('')',但无法在另一个项目中管理。 该组件是在 Vue.js 中使用 Javascript 实现的,我正在尝试在另一个使用支持 typescript 的 Vue.js 的项目中使用。

我已经尝试在我的项目main.ts中声明,但还是不行:

从'/src/components/toast/js/index'导入VueToast;

Vue.use(VueToast);

你知道我忘了声明什么吗?

【问题讨论】:

    标签: typescript vue.js vue-component


    【解决方案1】:

    要将 $toast 添加到 Vue 组件实例类型,请在 .d.ts 文件中声明以下 type augmentation(例如,在 src/shims-vue.d.ts 中):

    Vue 2:

    import Vue from 'vue'
    
    declare module 'vue/types/vue' {
      interface Vue {
        $toast: (msg: string) => void;
      }
    }
    

    Vue 3:

    declare module '@vue/runtime-core' {
      interface ComponentCustomProperties {
        $toast: (msg: string) => void;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 2020-01-14
      • 2021-11-22
      • 2021-03-07
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 2022-10-21
      • 1970-01-01
      相关资源
      最近更新 更多