vue3:自定义js文件(插件或配置)

原文地址
在vue3中自定义的js文件,如果需要设置全局this.xxx调用方式的话,需要给方法、变量、常量export出去,调用install()方法
插件的功能范围没有严格的限制——一般有下面几种:

添加全局方法或者 property。如:vue-custom-element

添加全局资源:指令/过滤器/过渡等。如:vue-touch)

通过全局混入来添加一些组件选项。(如vue-router)

添加全局实例方法,通过把它们添加到 config.globalProperties 上实现。

一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router

export default {
  install: (app) => {
  }
 }

举例腾讯防水墙js调用文件:
v2

// TencentCaptcha.js
import Vue from 'vue';
const appId = '*********';
Vue.prototype.$txCaptcha = (cb) => {
  const t = new window.TencentCaptcha(appId, (rsp) => {
    t.destroy();
    cb(rsp);
  }, {});
  t.show();
};

// main.js
import './config/TencentCaptcha';

使用

export default {
// ...
methods:{
	getCode () {
		this.$txCaptcha((res) => {
		    this.txResult = res;
		});
	}
}
}

v3

// TencentCaptcha.js
const appId = '*********';
export default {
  install: (app) => {
    const Vue = app;
    Vue.config.globalProperties.$txCaptcha = (cb) => {
      const t = new window.TencentCaptcha(appId, (rsp) => {
        t.destroy();
        cb(rsp);
      }, {});
      t.show();
    };
  },
};
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import txCaptcha from './config/TencentCaptcha';
createApp(App).use(txCaptcha)

使用

<script setup lang="ts">
import {getCurrentInstance} from 'vue'
getCurrentInstance().appContext.config.globalProperties.$txCaptcha((res) => {
    this.txResult = res;
});
</script>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mosowe

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值