vue根据后端数据,v-for渲染不同样式
- 效果图
- 数据
[
{ "Type": "1", "number": "大西几", "id": "1" },
{ "Type": "3", "number": "小脑斧", "id": "1" },
{ "Type": "2", "number": "严白虎", "id": "1" },
{ "Type": "2", "number": "好的话", "id": "1" },
{ "Type": "1", "number": "打碎u", "id": "1" },
{ "Type": "3", "number": "熏悟空", "id": "1" },
{ "Type": "1", "number": "修勾", "id": "1" }
]
Type是选择第几个模板渲染
- 具体代码
<template>
<div class="about">
<div v-for="items in datas" :key="items.id">
<div v-if="items.Type === '1' ">
<div id="green">
<p> {{items.number}} <span>样式1</span></p>
</div>
</div>
<div v-else-if="items.Type === '2' ">
<div id="red">
<p> {{items.number}} <span>样式2</span></p>
</div>
</div>
<div v-else>
<div id="yellow">
<div id="left">
<p> {{items.number}} </p>
</div>
<div id="right">
<p> {{items.number}} <span>样式3</span></p>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "aboout",
data() {
return {
datas: [],
};
},
mounted() {
this.getData();
},
methods: {
getData() {
axios.get("/api/hello.json").then((res) => {
console.log(res.data);
this.datas = [];
res.data.forEach((ele) => {
this.datas.push({
Type: ele.Type,
number: ele.number,
id: ele.id,
});
});
});
},
},
};
</script>
<style scoped>
p {
margin: 0;
}
#green {
width: 100%;
height: 100px;
background-color: rgb(19, 241, 19);
}
#green p {
color: aliceblue;
font-size: 23px;
line-height: 100px;
}
#red {
width: 100%;
height: 50px;
background-color: rgb(219, 72, 72);
}
#red p {
color: aliceblue;
font-size: 23px;
line-height: 50px;
}
#yellow {
width: 100%;
height: 75px;
background-color: rgb(247, 247, 84);
}
#left {
width: 50px;
height: 75px;
background-color: rgb(79, 174, 218);
float: left;
}
#right {
width: 75%;
height: 50px;
float: right;
}
#right p {
color: rgb(241, 57, 72);
font-size: 23px;
line-height: 50px;
}
</style>
利用v-for 和v-if联系数据中的标识选择模板渲染,这样就可以实现一套相同数据渲染不同模板样式了。
代码很简单吧。