vue学习(六)异步组件加载
异步组件加载
首先准备-----简单的框架搭出来
<!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>