創(chuàng)建組件的兩種方法小結(jié)
1.全局注冊
2.局部注冊
var child=Vue.extend({})var parent=Vue.extend({})Vue.extend() 全局方法 生成構(gòu)造器,創(chuàng)建子類
使用基礎(chǔ) Vue 構(gòu)造器,創(chuàng)建一個“子類”。
這樣寫非常繁瑣。于是vue進行了簡化
使用Vue.component()直接創(chuàng)建和注冊組件:
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'})Vue.component()的第1個參數(shù)是標簽名稱,第2個參數(shù)是一個選項對象,使用選項對象的template屬性定義組件模板。
使用這種方式,Vue在背后會自動地調(diào)用Vue.extend()。
在選項對象的components屬性中實現(xiàn)局部注冊:
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>' } }})==局部注冊都放在選項對象中創(chuàng)建==
注意:這里是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>注冊一個parent的父組件。然后在父組件的選項對象中注冊一個child的子組件。將子組件child的標簽寫到父組件parent的template里面。
頁面上的樣式結(jié)構(gòu)就是
<div> <h1>我是父組件</h1> <h1>我是子組件</h1></div>
注意:用局部注冊的子組件不能單獨直接使用!
標簽掛在div里,會報錯
<div id='box'> <child></child></div>
結(jié)果會報錯。
以上這篇Vue 創(chuàng)建組件的兩種方法小結(jié)(必看)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
|
新聞熱點
疑難解答