基础案例:
<script>
export default {
name: "HelloWorld",
data() {
return {
msg: "切换",
data1: [
{ name: "nam1", age: 12, flag: true },
{ name: "nam2", age: 13, flag: false },
{ name: "nam3", age: 14, flag: true },
{ name: "nam4", age: 15, flag: true }
],
data2: [
{ name: "nam5", age: 16, flag: false },
{ name: "nam6", age: 17, flag: true },
{ name: "nam7", age: 18, flag: false },
{ name: "nam8", age: 19, flag: true },
{ name: "nam9", age: 20, flag: true }
],
data: []
};
},
created() {
this.data = this.data1;
},
methods: {
changeState() {
this.data = this.data == this.data1 ? this.data2 : this.data1;
}
},
render() {
return (
<div>
<button onClick={this.changeState}>{this.msg}</button>
<ul>
{
this.data.map((item, index) => {
return item.flag?
<li>
<h1>{item.name}</h1>
</li>
:
<li>
<h5>{item.name}</h5>
</li>
})
}
</ul>
</div>
);
}
};
</script>
-
效果图如下
案例:递归实现树形组件
<script>
export default {
name: "HelloWorld",
data() {
return {
data: [
{
name: "1",
children: [{ name: "1_1" }, { name: "1_2" }, { name: "1_3" }]
},
{
name: "2",
children: [{ name: "2_1" }, { name: "2_2" }]
},
{
name: "3",
children: [
{
name: "3_1",
children: [
{ name: "3_1_1" },
{
name: "3_1_2",
children: [
{
name: "3_1_2_1",
children:[
{
name:"3_1_2_1_1"
}
]
},
{ name: "3_1_2_2" },
{ name: "3_1_2_3" }
]
},
{ name: "3_1_3" }
]
}
]
},
{
name: "4",
children: [{ name: "4_1" }, { name: "4_2" }]
}
]
};
},
methods: {
diguiMethdo(data) {
return (
<ul>
{data.map((item, index) => {
return item.children ? (
<div>
<li onClick={this.test.bind(this, item.name)} id={item.name}>
{item.name}
</li>
<li>{this.diguiMethdo(item.children)}</li>
</div>
) : (
<li>{item.name} </li>
);
})}
</ul>
);
},
test(info) {
let p = document.getElementById(info);
let p2 = p.parentNode.childNodes[1];
p2.style.display = p2.style.display == "none" ? "inline" : "none";
}
},
render() {
return (
<div class="clearfix" id="box">
{this.diguiMethdo(this.data)}
</div>
);
}
};
</script>
<style>
.clearfix {
*zoom: 1;
}
.clearfix:before,
.clearfix:after {
display: table;
line-height: 0;
content: "";
}
.clearfix:after {
clear: both;
}
#box {
float: left;
height: 100%;
width: 200px;
background-color: aquamarine;
}
li {
list-style: none;
}
</style>
-
效果图如图二