Vue.extend的基本使用
阿新 • • 發佈:2020-12-19
技術標籤:Vue
使用extend自定義一個全屏loading元件
1、定義loading元件
import Vue from "Vue"; const LoadingCom = Vue.extend({ template:`<div style="position:fixed;left:0;right:0;width:100%;height:100%;z-index:999;background:#d8d8d8;color:#000;" id="aaa" > {{msg}} </div>`, props:{ msg:{ type:String, default:"" } }, created() {//還可以有其它的生命週期 console.log("元件生命週期"); } });
2、例項化loading元件資訊
function loading(msg){ const div = document.createElement("div"); div.setAttribute("id","aaa");//這裡注意ID要跟第一步的元件ID一致 document.body.append(div); new LoadingCom({//例項化元件資訊,這裡的props會替換掉第一步中元件的props props:{ msg:{ type:String, default:msg } } }).$mount("#aaa"); return () => {//返回一個方法,呼叫此方法會移除掉這個元件 document.body.removeChild(document.getElementById("aaa")); } }
3、掛載在全域性上
Vue.prototype.$load = loading;
4、在xxx.vue介面中使用
<template> <div id="app"> <el-button @click="show">按鈕</el-button> </div> </template> <script> export default { name:"App", methods:{ show(){ const load = this.$load("正在載入"); setTimeout(() => { load(); }, 2000); } } } </script> <style lang="scss"> </style>
5、如果控制檯出現這個錯誤,可以在vue.config.js中設定下面的引數配置(runtimeCompiler:true)