- 組件高級用法
遞歸組件
組件在它的模板內(nèi)可以遞歸地調(diào)用自己,只要給組件設(shè)置name的選項就可以了。設(shè)置name后,在組件模板內(nèi)就可以遞歸使用了,不過需要注意的是,必須給一個條件來限制遞歸數(shù)量,否則會拋出錯誤:max stack size exceeded。
<div id="app">
<child-component :count="1"></child-component>
</div>
<script>
Vue.component('child-component', {
name: 'child-component',
props: {
count: {
type: Number,
default: 1
}
},
template: '<div class="child"> \
<child-component :count="count+1" v-if="count < 3"> \
</child-component> \
</div>'
})
var app = new Vue({
el: '#app'
})
</script>
內(nèi)聯(lián)模板
在自定義組件中添加inline-template,組件就會把其內(nèi)容當做template模板。
在父組件中聲明的數(shù)據(jù)message和子組件中聲明的數(shù)據(jù)msg,兩個都可以渲染(如果同名,優(yōu)先使用子組件的數(shù)據(jù))。這反而是內(nèi)聯(lián)模板的缺點,就是作用域比較難理解,如果不是非常特殊的場景,建議不要輕易使用內(nèi)聯(lián)模板。
<div id="app">
<child-component inline-template :message="messages">
<div>
<h2>在父組件中定義子組件的模板</h2>
<p>{{ message }}</p>
<p>{{ msg }}</p>
</div>
</child-component>
</div>
<script>
Vue.component('child-component', {
props: ['message'],
data: function() {
return {
msg: '在子組件聲明的數(shù)據(jù)'
}
}
});
var app = new Vue({
el: '#app',
data: {
messages: '在父組件聲明的數(shù)據(jù)'
}
})
</script>
動態(tài)組件
Vue.js提供了一個特殊的元素<component>用來動態(tài)地掛載不同的組件,使用is特性來選擇要掛載的組件。
<div id="app">
<component :is="currentView"></component>
<button @click="handleChangeView('A')">切換到A</button>
<button @click="handleChangeView('B')">切換到B</button>
<button @click="handleChangeView('C')">切換到C</button>
</div>
<script>
var app = new Vue({
el: '#app',
components: {
comA: {
template: '<div>組件A</div>'
},
comB: {
template: '<div>組件B</div>'
},
comC: {
template: '<div>組件C</div>'
},
},
data: {
currentView: 'comA'
},
methods: {
handleChangeView: function (component) {
this.currentView = 'com' + component;
}
}
})
</script>
動態(tài)地改變currentView的值就可以動態(tài)掛載組件了。也可以直接綁定在組件對象上。
<div id="app">
<component :is="addComp"></component>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
addComp: 'coma'
},
components: {
coma: {
template: '<div>動態(tài)掛載組件</div>'
}
}
})
</script>