異步組件加載
首先准備-----簡單的框架搭出來
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>異步組件加載</title> <meta name="viewport" content="width=device-width ,initial-scale=1"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <App></App> </div> <script> const App={ data(){ return{ msg:'異步組件加載' } }, template:`<div>{{msg}}</div>`, }; let app = new Vue({ el:'#app', template:``, components:{ App } }) </script> </body> </html>
在新建一個Text.js文件
export default { data() { return { msg: '小朋友' } }, template: `<div>{{msg}}</div>`, }
總代碼
1. 里面標簽的改變
2.剛開始只有vue.js的加入 在點擊之后 Text.js被加載
3.要用一個工廠函數
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>異步組件加載</title> <meta name="viewport" content="width=device-width ,initial-scale=1"> <script src="../no2_組件/vue.js"></script> <!--<script src="https://cdn.jsdelivr.net/npm/vue"></script>--> </head> <body> <div id="app"> <App></App> </div> <script type="module"> const App = { data() { return { isShow:false } }, methods:{ asyncLoad(){ this.isShow = !this.isShow } }, template: `<div> <button @click="asyncLoad">異步組件加載</button> <Test v-if="isShow"></Test> </div>`, components: { Test:()=>import('./Test.js') // 工廠函數 import導入 } }; let app = new Vue({ el: '#app', template: ``, components: { App } }) </script> </body> </html>