一 外部引入文件:(全局注册)
//建模版 var mycomponent=Vue.extend( {template:"<div><a href='#'>我爱Javascript!</div>"} ); //注册组件 Vue.component('my-component',mycomponent);
页面引用:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="../../vue.js"></script> <!-- 加载自定义元素封装的html模板 --> <script src="exm.js"></script> </head> <body> <div id="exm"> <my-component></my-component> </div> <script> //渲染时自动解析自定义元素及绑定内容 var vm=new Vue( { el:"#exm" } ); </script> </body> </html>
二 局部注册:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="../../vue.js"></script> </head> <body> <div id="exm"> <far-component></far-component> <!-- <my-component></my-component> --> </div> <script> var myComponent=Vue.extend( { template:"<div>我的Javascript</div>" } ); var far=Vue.extend( { template:"<div>我爱Javascript!<my-component></my-component></div>", components: { "my-component":myComponent //不用全局注册myComponent,这里在far-component中局部注册了myComponent,并只能far-compoennt元素中解析 } } ); /* Vue.component("my-component",myComponent);//全局注册后,亦可以全局使用*/ Vue.component("far-component",far); new Vue( { el:"#exm" } ); </script> </body> </html>