最近在做类似论文生成的一个系统,比较复杂,简单来说就是文字、图表的展示,但是顺序不固定,所以有动态渲染dom的需求,以下是我写的小demo,以作记录。
<template>
<div id="app">
<div v-for="item in orderedDivs" :key="item.id" :class="item.class">
<!-- 内容可以根据需要动态插入 -->
{{ item.content || '这里是内容区' }}
</div>
<el-button @click="handle">随机打乱</el-button>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
order: ['content', 'table', 'image'],
divsData: [
{ id: 'content', class: 'content', content: '内容部分' },
{ id: 'image', class: 'img', content: '图片部分' },
{ id: 'table', class: 'table', content: '表格部分' },
],
orderedDivs: [],
};
},
activated() {
console.log('activated');
(this.order = ['table', 'image', 'content']), this.getData();
},
methods: {
getData() {
console.log('this.order');
this.orderedDivs = this.order.map(id => this.divsData.find(div => div.id === id));
},
handle() {
this.order.sort(() => this.getRandomInt(-1, 1));
this.getData()
},
getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
},
};
</script>
<style scoped>
/* 样式可以根据需要进行调整 */
.content,
.img,
.table {
height: 100px;
width: 100px;
margin-bottom: 20px;
}
.content{
background-color: aquamarine;
}
.img{
background-color: beige;
}
.table{
background-color: lightpink;
}
</style>