vue3如何自定义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)

使用

<script setup lang="ts">
import {getCurrentInstance} from 'vue'
getCurrentInstance().appContext.config.globalProperties.$txCaptcha((res) => {
    this.txResult = res;
});
</script>

 

vue加载自定义的js文件

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

效果图

这里写图片描述

遇见的问题

怎么加载自定义的js文件

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

export default{
  install(Vue){
      var tpl;
      // 弹出框
      Vue.prototype.showAlter = (title,msg) =>{
          var alterTpl = Vue.extend({     // 1、创建构造器,定义好提示信息的模板
                  template: '<div id="bg">'
                       + '<div class="jfalter">'
                       + '<div class="jfalter-title" id="title">'+ title +'</div>'
                       + '<div class="jfalter-msg" id="message">'+ msg +'</div>'
                       + '<div class="jfalter-btn" id="sureBtn" v-on:click="hideAlter">确定</div>'
                       + '</div></div>'
          });
          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('提示','服务器请求失败');

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

 写在前面目前大部分的项目,基本上都采用了前后端分离的框架。随着项目的不断做大做强,框架就会变得很庞大。那么前端的框架,也是会变得不断的臃肿。不同的模块项目前端,可能有些公共的方法,都是共用 ...