<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>全局组件</title> </head> <body> <div id="app"> <father></father> <son></son> <hr> <div :is='component'></div> <button @click="toggle">切换</button> </div> <template id="father"> <div> 我是父组件 </div> </template> <template id="son"> <div> 我是子组件 </div> </template> <script src="vue.js"></script> <script> Vue.component("father",{ template:"#father" }); Vue.component("son",{ template:"#son" }); new Vue({ el:"#app", data:{ component:'son' }, methods:{ toggle(){ this.component=this.component=='son'?"father":'son'; } } }); </script> </body> </html>
结果截图: