自定义全局$loading加载组件(通过JS进行调用)

文章讲述了如何在Vue中创建一个LoadingToast.vue组件,通过Vue.extend结合数据动态渲染,并在LoadingToast.js中注册为全局组件,提供$loading.show和$loading.hide方法进行显示和隐藏。最后在main.js中引入并使用Vue.use()安装。
摘要由CSDN通过智能技术生成

1.先写一个loading组件,定义为LoadingToast.vue

里面定义两个参数:

  1. showLoading用于控制Loading组件显示与否;
  2. tips用于显示提示文字,默认为’加载中…'。

2.创建一个LoadingToast.js文件,将Loading组件通过install注册为全局组件

import Vue from 'vue;
import LoadingToast from '/components/LoadingToast ';
const Loading = {};
let showLoading = false;
let loadingNode = null;
const LoadingStructor = Vue.extend(LoadingToast);

Loading.installed = false;
Loading.install = function(Vue){
	if (Loading.installed) { return };
	// 添加实例方法
	Vue.prototype.$loading = {};
	Vue.prototype.$loading.show = tips => {
		if (showLoading) { return };
		loadingNode = new LoadingStructor({
			data: {
				showLoading,
				tips
			}
		});
		loadingNode.$mount();
		document.body.append(loadingNode.$el);
		showLoading = true;
		loadingNode.showLoading = showLoading;
		Loading.installed = true;
	};

	Vue.prototype.$loading.hide = () => {
		showLoading = false;
		loadingNode.showLoading = showLoading;
	}
};

export default Loading;

3.在main.js中引入LoadingToast.js,并通过全局方法 Vue.use() 使用;

import Loading form '**/LoadingToast.js'
Vue.use(Loading)

涉及知识点

  1. 关于Vue.extend(应用场景及API解析)
    • 组件模板非事先定义好的,若需要从接口动态渲染组件;
    • 若要实现一个类似于 window.alert() 提示组件要求像调用 JS 函数一样调用它;
      这时候,Vue.extend + vm.$mount 组合就派上用场了。

Vue.extend( options )
参数:{Object} options
用法:使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象;
data 选项是特例,需要注意: 在 Vue.extend() 中它必须是函数;

<div id="mount-point"></div>
// 创建构造器
var Profile = Vue.extend({
  template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
  data: function () {
    return {
      firstName: 'Walter',
      lastName: 'White',
      alias: 'Heisenberg'
    }
  }
})
// 创建 Profile 实例,并挂载到一个元素上。
new Profile().$mount('#mount-point');
  1. 关于Vue.use(Plugin)及Install

1.应用场景
Vue.use在使用时实际是调用了该插件的install方法,所以引入的当前插件如果含有install方法我们就需要使用Vue.use();
2.参数:plugin
Object | Function
3.用法
安装 Vue.js 插件。
如果插件是一个对象,必须提供 install 方法。
如果插件是一个函数,它会被作为 install 方法,install 方法调用时,会将 Vue 作为参数传入。
4.特别说明
该方法需要在调用 new Vue() 之前被调用。
install 方法被同一个插件多次调用,插件将只会被安装一次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值