創建組件的兩種方法小結
1.全局注冊
2.局部注冊
var child=Vue.extend({}) var parent=Vue.extend({})
Vue.extend() 全局方法 生成構造器,創建子類
使用基礎 Vue 構造器,創建一個“子類”。
這樣寫非常繁瑣。于是vue進行了簡化
使用Vue.component()直接創建和注冊組件:
Vue.component(id,options) 全局方法 用來注冊全局組件
id 是string類型,即是注冊組件的名稱
options 是個對象
// 全局注冊,my-component1是標簽名稱 Vue.component('my-component1',{ template: '<p>This is the first component!</p>' }) var vm1 = new Vue({ el: '#app1' })
Vue.component()的第1個參數是標簽名稱,第2個參數是一個選項對象,使用選項對象的template屬性定義組件模板。
使用這種方式,Vue在背后會自動地調用Vue.extend()。
在選項對象的components屬性中實現局部注冊:
var vm2 = new Vue({ el: '#app2', components: { // 局部注冊,my-component2是標簽名稱 'my-component2': { template: '<p>This is the second component!</p>' }, // 局部注冊,my-component3是標簽名稱 'my-component3': { template: '<p>This is the third component!</p>' } } })
==局部注冊都放在選項對象中創建==
注意:這里是components,里面可以定義多個組件。
簡化后是這樣的寫法
<body> <p id='box'> <parent> </parent> </p> <script src='js/vue.js'></script> <script> Vue.component('parent',{ template:`<p><h1>我是父組件</h1><child></child></p>`, components:{ 'child':{ template:`<h1>我是子組件</h1>` } } }) new Vue({ el:'#box' }) </script> </body>
注冊一個parent的父組件。然后在父組件的選項對象中注冊一個child的子組件。將子組件child的標簽寫到父組件parent的template里面。
頁面上的樣式結構就是
<p> <h1>我是父組件</h1> <h1>我是子組件</h1> </p>
注意:用局部注冊的子組件不能單獨直接使用!
標簽掛在p里,會報錯
<p id='box'> <child></child> </p>
上面是我整理給大家的,希望今后會對大家有幫助。
相關文章:
在angular中基于ng-alain如何定義自己的select組件?
在vue中如何實現watch監聽對象及對應值的變化
如何解決Vue不能檢測數組或對象變動方面問題?
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com