Vue.extend( options )
--參數(shù):
{Object} options
--用法:
使用基礎(chǔ) Vue 構(gòu)造器,創(chuàng)建一個(gè)“子類”。參數(shù)是一個(gè)包含組件選項(xiàng)的對(duì)象。
data 選項(xiàng)是特例,需要注意 - 在 Vue.extend() 中它必須是函數(shù)
接下來看看官方文檔的用法
<div id="mount-point"></div>
// 創(chuàng)建構(gòu)造器
var Profile = Vue.extend({
template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
data: function () {
return {
firstName: 'Walter',
lastName: 'White',
alias: 'Heisenberg'
}
}
})
// 創(chuàng)建 Profile 實(shí)例,并掛載到一個(gè)元素上。
new Profile().$mount('#mount-point')
結(jié)果如下:
<p>Walter White aka Heisenberg</p>
由此看出extend()可以創(chuàng)建一個(gè)構(gòu)造函數(shù)。創(chuàng)建一個(gè)實(shí)例對(duì)象可以用來添加一個(gè)dom元素。那么也可以用它來創(chuàng)建一個(gè)過場的loading效果。
首先,創(chuàng)建一個(gè)Vue實(shí)例,在其中添加一個(gè)點(diǎn)擊 開始loading 的方法 btnClick
<div id="root">
<button @click='btnClick'>開始loading</button>
</div>
new Vue({
el: "#root",
data(){
return {
message: "正在加載..."
}
},
methods: {
btnClick() {
}
}
})
利用Vue.extend()創(chuàng)建一個(gè)模板構(gòu)造函數(shù)
const Loadingcomponent = Vue.extend({
template: "<div id='loading'>{{msg}}</div>",
props: {
msg: {
type: String,
default: "loading..."
}
}
})
聲明一個(gè) loading 方法
function loading( msg ) {
let div = document.createElement("div")
div.setAttribute("id" , "loading-temp")
document.body.appendChild(div) // 創(chuàng)建一個(gè)dom元素,將其添加到body中,后面loading渲染后將其替換。
new Loadingcomponent({ // 這里傳入的對(duì)象會(huì)替換掉模板里面相同的內(nèi)容(props , msg )
props: {
msg: {
type: String,
default: msg // 將默認(rèn)值改變成傳入的 msg
}
}
}).$mount("#loading-wrapper") // 渲染loading , 并將 loading-temp 替換成 loading
return () => { // 這里會(huì)返回一個(gè)函數(shù),過場動(dòng)畫完成之后就可以清除loading
document.body.removeChild(document.querySelector("#loading"))
}
}
Vue.prototype.$loading = loading // 將loading函數(shù)添加到vue的原型對(duì)象,方便以后的vue實(shí)例調(diào)用
寫入 loading 的默認(rèn)樣式
<style>
#loading{
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0,0,0,.5);
color: #fff;
line-height: 100vh;
text-align: center;
}
</style>
在vue實(shí)例中添加具體的實(shí)現(xiàn)邏輯
new Vue({
el: "#root",
data(){
return {
message: "正在加載..."
}
},
methods: {
btnClick() {
let hide = this.$loading("正在加載...") // 點(diǎn)擊按鈕調(diào)用之前創(chuàng)建的 loading 函數(shù),返回一個(gè)清除過場的回調(diào)函數(shù)
setTimeout(() => {
hide() // 設(shè)定等待時(shí)間,清除過場
} , 2000)
}
}
})
然后就可以點(diǎn)擊按鈕出現(xiàn)一個(gè) 正在加載... 的界面