您现在的位置是:网站首页> 编程资料编程资料

vue3如何自定义js文件(插件或配置)_vue.js_

2023-05-24 418人已围观

简介 vue3如何自定义js文件(插件或配置)_vue.js_

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)

使用

vue加载自定义的js文件

在做项目中需要自定义弹出框。就自己写了一个。

效果图

这里写图片描述

遇见的问题

怎么加载自定义的js文件

vue-插件这必须要看。然后就是自己写了。

export default{ install(Vue){ var tpl; // 弹出框 Vue.prototype.showAlter = (title,msg) =>{ var alterTpl = Vue.extend({ // 1、创建构造器,定义好提示信息的模板 template: '
' + '
' + '
'+ title +'
' + '
'+ msg +'
' + '
确定
' + '
' }); tpl = new alterTpl().$mount().$el; // 2、创建实例,挂载到文档以后的地方 document.body.appendChild(tpl); } Vue.mixin({ methods: { hideAlter: function () { document.body.removeChild(tpl); } } }) } }

使用

import jFAltre from '../../assets/jfAletr.js'; import Vue from 'vue'; Vue.use(jFAltre);
this.showAlter('提示','服务器请求失败');

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

-六神源码网