vue-子組件創建/註冊/使用流程

  • 2021 年 12 月 26 日
  • 筆記

流程分為三步

 

非單文件組件:(實際不用,因為很麻煩,框架都是多文件組件)

局部註冊

1.創建一個組件

const school = Vue.extend({
   // 傳入配置對象
   // 子組件配置對象不要寫el,根據vm引入作用到對應區域
   //  data屬性需要寫成函數
template:``,
  name:'school', data(){ return { // 返回需要的data對象,因為data函數返回值是一個新的拷貝,而data對象是共同引用 } } })

2.註冊該組件

// 在vm實例的配置對象中加入components屬性

new Vue({
   components:{
       School:school,
       Student:student  
// 最好是直接簡寫
school, } })

3.在需要的模板中使用組件標籤

註冊後就可以復用這些組件

// 標籤名就是組件名 
<School></School>

 

注意事項:

(1)全局註冊的方法

//調用component方法
Vue.component('hello',hello) 
參數為 組件標籤名,組件名

 (2)組件標籤名的命名規範

方法1:
//
單個單詞,首字母大寫 <School> //多個單詞,多單詞首字母大寫 <MySchool>

方法2:
//全小寫
<school>

//全小寫 - 間隔
<my-school>

 (3)組件名在vue開發者工具中的識別

在組件配置項中的name屬性決定,name沒寫則選擇註冊中的組件標籤名

 

Tags: