我正在尝试创建一个自定义和可重用的数据表组件。但是我希望能够使每个页面上的外观都不同。我希望能够将行数据传递到组件中并自定义布局,但功能保持不变。我不明白该怎么做。这是我要尝试做的一个例子。
例如,在一个页面上,我想要这种模板,而在另一页面上,我想要不同的模板。但是功能相同。
<datatable>
<div v-for="row in rows" class="header" @click="sortBy(row.field)">row.title</div>
<div v-for="row in rows">row.value</div>
</datatable>
但是在另一页上,我想要一个不同的布局
<datatable>
<h1>
<span v-for="row in rows" @click="sortBy(row.field)">row.title</span>
</h1>
<h3 v-for="row in rows">row.value</h3>
</datatable>
我想不出任何可能的办法。应该将sortBy函数包含在组件内部,但是如何实现呢?
答案 0 :(得分:0)
./ src / components / dataTableComponent.vue
<template>
<datatable>
<div v-if="!withTitles">
<div v-for="(row, index) in rows" :key="index" class="header" @click="sortBy(row.field)">row.title</div>
<div v-for="(row, index) in rows" :key="index">row.value</div>
</div>
<div v-id="withTitles">
<h1>
<span v-for="(row, index) in rows" :key="index" @click="sortBy(row.field)">row.title</span>
</h1>
<h3 v-for="(row, index) in rows" :key="index">row.value</h3>
</div>
</datatable>
</template>
<script>
export default {
name: 'dataTableComponent',
props: ['rows', 'withTitles'],
data () {
return {
}
},
methods: {
sortBy(field){
//Code to ordre this.rows
}
}
}
</script>
<template>
<div>
<h2>No titles</h2>
<dataTableComponent :rows="rows" :withTitles="ture">
<h2>With Titles</h2>
<dataTableComponent :rows="rows">
</div>
</template>
<script>
import dataTableComponent from 'src/components/dataTableComponent.vue';
export default {
components: {dataTableComponent},
data () {
return {
rows: ['AAA', 'BBB', 'CCC']
}
}
}
</script>
答案 1 :(得分:0)
您可以使用vue插槽:https://vuejs.org/v2/guide/components-slots.html
datatable.vue
<template>
<div>
<slot name="table-slot"></slot>
</div>
</template>
<script>
export default {
name: 'datatable'
}
</script>
sampleComp1.vue
<template>
<div>
<datatable>
<div slot="table-slot">
// add your template data
</div>
</datatable>
</div>
</template>
<script>
import datatable from './datatable.vue';
export default {
name: 'sampleComp1',
data() {
rows: [] // put your values in this array
},
components: {
datatable
},
methods: {
sortBy(field) {
// do something
}
}
}
</script>
sampleComp2.vue
<template>
<div>
<datatable>
<div slot="table-slot">
// add your template data
</div>
</datatable>
</div>
</template>
<script>
import datatable from './datatable.vue';
export default {
name: 'sampleComp2',
data() {
rows: [] // put your values in this array
},
components: {
datatable
},
methods: {
sortBy(field) {
// do something
}
}
}
</script>