Vue 創建組件的兩種方法


地址:https://blog.csdn.net/cofecode/article/details/74634301

 

創建組件的兩種方法

1.全局注冊 
2.局部注冊

var child=Vue.extend({}) var parent=Vue.extend({})
  • 1
  • 2
  • 3

Vue.extend() 全局方法 生成構造器,創建子類

使用基礎 Vue 構造器,創建一個“子類”。

這樣寫非常繁瑣。於是vue進行了簡化

使用Vue.component()直接創建和注冊組件:

Vue.component(id,options) 全局方法 用來注冊全局組件

id 是string類型,即是注冊組件的名稱 
options 是個對象

// 全局注冊,my-component1是標簽名稱 Vue.component('my-component1',{ template: '<div>This is the first component!</div>' }) var vm1 = new Vue({ el: '#app1' })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Vue.component()的第1個參數是標簽名稱,第2個參數是一個選項對象,使用選項對象的template屬性定義組件模板。 
使用這種方式,Vue在背后會自動地調用Vue.extend()。

在選項對象的components屬性中實現局部注冊:

var vm2 = new Vue({ el: '#app2', components: { // 局部注冊,my-component2是標簽名稱 'my-component2': { template: '<div>This is the second component!</div>' }, // 局部注冊,my-component3是標簽名稱 'my-component3': { template: '<div>This is the third component!</div>' } } })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

==局部注冊都放在選項對象中創建==

注意:這里是components,里面可以定義多個組件。

簡化后是這樣的寫法

<body> <div id='box'> <parent> </parent> </div> <script src='js/vue.js'></script> <script> Vue.component('parent',{ template:`<div><h1>我是父組件</h1><child></child></div>`, components:{ 'child':{ template:`<h1>我是子組件</h1>` } } }) new Vue({ el:'#box' }) </script> </body>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

注冊一個parent的父組件。然后在父組件的選項對象中注冊一個child的子組件。將子組件child的標簽寫到父組件parent的template里面。

頁面上的樣式結構就是

<div> <h1>我是父組件</h1> <h1>我是子組件</h1> </div>
  • 1
  • 2
  • 3
  • 4

注意:用局部注冊的子組件不能單獨直接使用!

標簽掛在div里,會報錯

<div id='box'> <child></child> </div> 結果會報錯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM