likes
comments
collection
share

vue3.0 + ts 引入微信sdk

作者站长头像
站长
· 阅读数 15

前置清单

  • vue3.0
  • ts
  • vue-cli
  • weixin-js-sdk

微信平台端配置

1.安装SDK

    npm install weixin-js-sdk --save

vue3.0 + ts 引入微信sdk package.json文件中出现weixin-js-sdk,就安装成功了!

2.微信sdk的封装

  • 在src 文件夹中创建 wxsdk/index.ts 文件
import wx from "weixin-js-sdk";
import type { App } from "vue";

const plugin = {
  install(Vue: App): void {
    Vue.config.globalProperties.$wechat = wx;
    Vue.config.globalProperties.wechat = wx;
  },
};

export default plugin;
export const install = plugin.install;

这个时候会出现报错:

vue3.0 + ts 引入微信sdk

无法找到模块“weixin-js-sdk”的声明文件。“F:/web/vue-ts-eslint/node_modules/_weixin-js-sdk@1.6.0@weixin-js-sdk/index.js”隐式拥有 "any" 类型。 尝试使用 npm i --save-dev @types/weixin-js-sdk (如果存在),或者添加一个包含 declare module 'weixin-js-sdk'; 的新声明(.d.ts)文件

  • 报错处理:在src 文件夹中创建 index.d.ts 文件
    declare module "weixin-js-sdk";
  • mian.ts修改
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import wxsdk from "./wxsdk";

createApp(App).use(store).use(router).use(wxsdk).mount("#app");

vue页面使用微信sdk

vue3.0 + ts 引入微信sdk

Property 'wechat' does not exist on type 'CreateComponentPublicInstance<{ [x: string & `on{string}]: ((...args: any[]) => any) | undefined; } | { [x: string & on${string}`]: undefined; }, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, ... 10 more ..., {}>'.

  • 报错处理:在src 文件夹中创建 type.d.ts 文件
export {};
import wx from "weixin-js-sdk";

declare module "@vue/runtime-core" {
  interface ComponentCustomProperties {
    $wechat: wx;
  }
}

这样就可以了!