18_非單檔案元件
阿新 • • 發佈:2021-11-13
Vue使用元件的三大步驟:
一、定義元件(建立元件) 二、註冊元件 三、使用元件(寫元件標籤)一、如何定義一個元件? 使用Vue.extend(options)建立,其中options和new Vue(options)時傳入的那個options幾乎一樣,但也有點區別; 區別如下: 1.el不寫,why?---最終的所有的元件都要被一個vm管理,由vm中的el決定服務哪個容器 2.data必須寫成函式,why?---避免元件被複用時,資料存在引用關係 備註:使用template可以配置元件結構
程式碼練習:
第一步:建立元件
第二步:註冊元件
區域性註冊:
全域性註冊:
第三步:編寫元件標籤
幾個注意點:
1.關於元件名: 一個單片語成: 第一種寫法(首字母小寫):school 第二種寫法(首字母大寫):School 多個單片語成:2.關於元件標籤:
第一種寫法:<school></school> 第二種寫法:<school/> 備註:不使用腳手架時,<school/>會導致後續元件不能渲染定義一個總的元件:
例項程式碼:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>元件的巢狀</title> 8 <script type="text/javascript" src="../js/vue.js"></script> 9 </head> 10 <body> 11 <!-- 準備好一個容器 --> 12 <div id="root"> 13 <!--編寫元件標籤--> 14 <app></app> 15 </div> 16 </body> 17 <script type="text/javascript"> 18 Vue.config.productionTips = false //阻止vue在啟動時生成生產提示 19 //定義student元件 20 const student = Vue.extend({ 21 name:'student', 22 template:` 23 <div> 24 <h2>學生名稱:{{name}}</h2> 25 <h2>學生年齡:{{age}}</h2> 26 </div> 27 `, 28 data(){ 29 return { 30 name:'王麻子', 31 age:18 32 } 33 } 34 }) 35 //定義school元件 36 const school = Vue.extend({ 37 name:'school', 38 template:` 39 <div> 40 <h2>學校名稱:{{name}}</h2> 41 <h2>學校地址:{{address}}</h2> 42 <student></student> 43 </div> 44 `, 45 data(){ 46 return { 47 name:'尚矽谷', 48 address:'上海' 49 } 50 }, 51 //註冊元件(區域性) 52 components:{ 53 student 54 } 55 }) 56 //定義hello元件(與student平級) 57 const hello = Vue.extend({ 58 template:`<h1>{{msg}}</h1> `, 59 data(){ 60 return { 61 msg:'歡迎學習Vue' 62 } 63 } 64 }) 65 //定義app元件 66 const app = Vue.extend({ 67 template:` 68 <div> 69 <hello></hello> 70 <school></school> 71 </div> 72 `, 73 components:{ 74 school, 75 hello 76 } 77 }) 78 //建立vm 79 new Vue({ 80 //template:`<app></app>`,(相當於容器裡面的編寫元件標籤<app></app) 81 el:'#root', 82 //註冊元件(區域性註冊) 83 components:{app} 84 }) 85 </script> 86 </html>