1. 程式人生 > 其它 >vue-元件(分類)

vue-元件(分類)

一、元件的分類

元件可以分類為:全域性元件和區域性元件。

1、全域性元件

全域性元件可以在所有的vue例項中使用。使用Vue.component定義全域性元件。

2、區域性元件

區域性元件只能在該vue例項中使用。使用Vue中的components選項定義區域性元件。

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>定義元件</title>
 6   <!--引入vue-->
7 <script src="../js/vue.js"></script> 8 </head> 9 <body> 10 11 <div id="hello"> 12 <!-- 全域性元件 --> 13 <hello></hello> 14 <yaya></yaya> 15 <!-- 區域性元件 --> 16 <my-world></
my-world> 17 </div> 18 19 <script> 20 //自定義元件 方式1:使用元件構造器定義元件 21 //第一步:使用Vue.extend建立元件構造器 22 var MyComponent=Vue.extend({ 23 template:'<h3>HelloWorld</h3>' 24 }) 25 //第二步:使用Vue.component建立元件 26 Vue.component(
'hello',MyComponent) 27 28 29 //自定義元件 方式2:直接建立元件 30 Vue.component('yaya',{ //該方法定義的元件為全域性元件 31 template:'<h2>yaya是個小可愛</h2>' 32 }) 33 34 //vue例項 35 let vm = new Vue({ //vm其實也是一個元件,是根元件Root 36 el:'#hello', 37 components:{ //定義區域性元件 38 'my-world':{ 39 template:'<h1>你好,我是你自定義的區域性元件,只能在當前vue例項中使用</h1>' 40 } 41 } 42 }); 43 </script> 44 </body> 45 </html>