ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 一、概述 组件有四种用法: 1. 先定义,后注册 2. 同时定义并注册组件 3. 使用HTML模版template 4. 使用HTML模版script ## 二、先定义,后注册 ``` ar demo1 = Vue.extend({ template:'<h1>示例1</h1>' }); Vue.component('demo1',demo1); ``` ## 三、同时定义并注册组件 ``` Vue.component('demo2',{ template:'<h1>示例2</h1>' }); ``` ## 四、使用HTML模版template 这种方式与上面很大的不同点是使用了HTML模板,而这种模板在IDE中是有智能提示与纠错的,因而更方便于使用,所以一般我们推荐使用这种方式定义与注册组件。 ``` <template id="demo3"> <h1>示例3</h1> </template> Vue.component('demo3',{ template:'#demo3' }); ``` ## 五、使用HTML模版script 这第四种方式其实和第三种用法是完全一样的,不同之处在于其模版标签不同; ``` <script type="x-template" id="demo4"> <h1>示例4</h1> </script> Vue.component('demo3',{ template:'#demo3' }); ``` ## 六、例子 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>组件</title> </head> <body> <template id="demo3"> <h1>示例3</h1> </template> <script type="x-template" id="demo4"> <h1>示例4</h1> </script> <div id="app"> <demo1></demo1> <demo2></demo2> <demo3></demo3> <demo4></demo4> </div> <script src="../../../js/vue/vue/1.0/vue.js"></script> <script type="application/javascript"> //1、定义组件 var demo1 = Vue.extend({ template:'<h1>示例1</h1>' }); //2、注册组件 Vue.component('demo1',demo1); //第二种方法 Vue.component('demo2',{ template:'<h1>示例2</h1>' }); //第三种方法 Vue.component('demo3',{ template:'#demo3' }); //第四种方法 Vue.component('demo4',{ template:'#demo4' }); new Vue({ el:'#app' }); </script> </body> </html> ```