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('提示','服务器请求失败');
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于vue3如何自定义js文件(插件或配置)的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did122411