如何在带有打字稿的 vue.js 中使用 javascript 组件? [英] How to use a javascript component in vue.js with typescript?

查看:27
本文介绍了如何在带有打字稿的 vue.js 中使用 javascript 组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<块引用>

从'../ToastNotification'导入ToastNotification;从 './api' 导入 Api;const VueToast = (Vue, options = {}) =>{const 方法 = Api(Vue, options);Vue.$toast = 方法;Vue.prototype.$toast = 方法;};ToastNotification.install = VueToast;导出默认 ToastNotification;

在 index.js 中我声明:

<块引用>

从'./toast/js/index'导入VueToast;Vue.use(VueToast);

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

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

我已经尝试在我的项目中在 main.ts 中声明,但仍然不起作用:

<块引用>

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

Vue.use(VueToast);

你知道我忘了申报什么吗?

解决方案

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

Vue 2:

从 'vue' 导入 Vue声明模块'vue/types/vue'{界面 Vue {$toast: (msg: string) =>空白;}}

Vue 3:

声明模块 '@vue/runtime-core' {接口 ComponentCustomProperties {$toast: (msg: string) =>空白;}}

I have a component defined in a project and want to expose like this, in order to use in another project:

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;

In index.js I declare :

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

Vue.use(VueToast);

And in another project I npm install this project as a library but this.$toast('message') is not recognized. It said that "Property '$toast' does not exist on type '' "

I mention that I managed to use inside the project, another class the 'this.$toast('')', but can't manage in another project. The component is implemented in Vue.js using Javascript and I'm trying to use in another project that uses Vue.js that supports typescript.

I already tried to declare in my project in main.ts, but still does not work:

import VueToast from'/src/components/toast/js/index';

Vue.use(VueToast);

Do you have any idea about what I forgot to declare?

解决方案

To add $toast to the Vue component instance type, declare the following type augmentation in a .d.ts file (e.g., in 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;
  }
}

这篇关于如何在带有打字稿的 vue.js 中使用 javascript 组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆