使用<component>
標簽加上is
實現
<div id="dynamic-component-demo" class="demo">
<button
v-for="tab in tabs"
v-bind:key="tab"
v-bind:class="['tab-button', { active: currentTab === tab }]"
v-on:click="currentTab = tab"
>
{{ tab }}
</button>
<component v-bind:is="currentTabComponent" class="tab"></component>
</div>
Vue.component('tab-home', {
template: '<div>Home component</div>'
})
Vue.component('tab-posts', {
template: '<div>Posts component</div>'
})
Vue.component('tab-archive', {
template: '<div>Archive component</div>'
})
new Vue({
el: '#dynamic-component-demo',
data: {
currentTab: 'Home',
tabs: ['Home', 'Posts', 'Archive']
},
computed: {
currentTabComponent: function() {
return 'tab-' + this.currentTab.toLowerCase()
}
}
})
在<ul>
、<ol>
、<table>
和 <select>
中,盡量勿使用如:
<table>
<tr-component></tr-component>
</table>
應使用,如:
<div id="app">
<table class="table">
<tbody>
<tr
is="price-component"
v-for="(item,key) in timeData"
:item="item"
:key="key"
></tr>
</tbody>
</table>
</div>
<script type="text/x-template" id="filter-component">
<tr>
<td>{{item.name}}</td>
<!-- 過濾順序:currency => dollarSign -->
<td>{{item.price|currency|dollarSign}}</td>
</tr>
</script>
const priceChild = {
props: {
item: {
type: Object,
required: true
}
},
template: '#filter-component',
filters: {
dollarSign(val) {
return `$ ${val}`
},
currency(val) {
// replace 方法會將值切分如 5500 => ['5','5','0','0']
// current: 每一個元件
// newVal: 這裡為 toFixed後的結果,5500.00
return val.toFixed(2).replace(/./g, (current, index, newVal) => {
return index && current !== '.' && (newVal.length - index) % 3 === 0
? ',' + current
: current
})
}
}
}
new Vue({
el: '#app',
data() {
return {
timeData: [
{
name: '薯條',
price: 20.555
},
{
name: '甜不辣',
price: 25
},
{
name: '黃金雞排',
price: 55000.65
}
]
}
},
components: {
'price-component': priceChild
}
})