1.先写一个loading组件,定义为LoadingToast.vue
里面定义两个参数:
showLoading
用于控制Loading组件显示与否;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)
涉及知识点
- 关于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');
- 关于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
方法被同一个插件多次调用,插件将只会被安装一次