Vue的異步組件

異步組件,顧名思義,按需加載組件。

在vue的文檔中,除了異步組件的高級使用方法外,介紹了三個異步組件的解決方案

在介紹異步組件的解決方案之前,先說明一下組件的注冊:

1、全局組件注冊:

通過import Vue from 'vue' 在環境中引入Vue對象 ,并調用其component方法注冊全局組件

Vue.component('async-webpack-component-name',function(resolve){

? ? require(['./my-async-component'], resolve)

})

2、局部注冊組件

在vue對象的components中注冊局部組件

new Vue({

? ? // ...

? ? components: {

? ? ? ? 'my-component':()=>import('./my-async-component')

? ? }

})

組件注冊說明完畢,下面介紹異步組件的具體實現方式:

1、借助于require與webpack的代碼分隔功能來實現

export default{

? ? data: () => ({

? ? ? ? key:'',

? ? ? ? value:'test'

? ? }),

? ? components: {

? ? ? ? 'zz': (resolve) => {

? ? ? ? // 這個特殊的 require 語法告訴 webpack,而這邊需要打包的vue組件的目錄是通過ajax拿到

? ? ? ? // 自動將編譯后的代碼分割成不同的塊,

? ? ? ? // 這些塊將通過 Ajax 請求自動下載。(這是官方說明,實際上代碼中的異步組件依然被webpack打包成一個js文件,需要在html中引入才能 ? ? ? ? ? 使用)

? ? ? ? require(['./'+ window.vue.key],resolve) ?//需要注意的是,目錄必須是字符串,且不能完全由變量代替

? ? }

},

? ? created() {

? ? ? ? window.vue=this

? ? },

? ? methods: {

? ? ? ? funConsole(word) {

? ? ? ? ? ? console.log(word)

? ? ? ? }

},

beforeRouteEnter(to,from,next) {

? ? next(vm => {

? ? ? ? vm.$http.post('url').then((response) => {

? ? ? ? ? ? vm.key='HH.vue'

? ? ? ? },(response) => {

? ? })

})

}

}

2、使用 Webpack 2 + ES2015 的語法返回一個Promise ?resolve 函數

export default{

data: () => ({

key:'',

value:'test'

}),

components: {

'zzz': () =>import('./'+ window.vue.key) //此處同上

},

created() {

window.vue=this

},

methods: {

funConsole(word) {

console.log(word)

}

},

beforeRouteEnter(to,from,next) {

next(vm => {

vm.$http.get('url').then((response) => {

vm.key='HH.vue'

},(response) => {

})

})

}

}

3、動態獲取服務端的組件

export default{

data: () => ({

key:'',

value:'test'

}),

components: {

'z':function(resolve,reject) {

window.vue.$http.get('/static/img/HH.js',).then((response) => {

let str = response.bodyText.replace('export default ','')

let obj =eval("("+ str +")")

resolve(obj)

},(response) => {

})

}

},

created() {

window.vue=this

},

methods: {

funConsole(word) {

console.log(word)

}

},

beforeRouteEnter(to,from,next) {

next(vm => {

vm.$http.get('url').then((response) => {

vm.key='HH.vue'

},(response) => {

})

})

}

}



1、2方法編譯輸出后,會多生成一個異步組件的Js文件,需要在html文件中引入,才能實現異步組件

而第三種無需在html中引入,通過后端傳入js文件url即可實現真真的異步組件

(水平有限,如有認識不足之處還望指出,謝謝)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容