父组件子组件实现闭合效果如下:这里点击不同的同学展示隐藏的div,同时没有被点击的同学隐藏div,
这个效果代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.title {
width: 120px;
border: 1px solid pink;
line-height: 36px;
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<collaspe>
<collaspe-item title="大学同学">大学同学1</collaspe-item>
<collaspe-item title="高中同学">高中同学1</collaspe-item>
<collaspe-item title="初中同学">初中同学1</collaspe-item>
</collaspe>
</div>
</body>
</html>
<script src="./node_modules//vue//dist//vue.min.js"></script>
<script>
//$children-获取子组件的实例 $parent--获取父组件的实例
Vue.component("collaspe", {
methods: {
handleChange(childId) {
this.$children.forEach(element => {
if (element._uid != childId) {
element.show = false;
}
});
}
},
template: `<div class = 'box'>
<slot></slot>
</div>`
});
Vue.component("collaspe-item", {
props: ['title'],
mounted() {
console.log(this.$parent)
},
methods: {
change() {
this.$parent.handleChange(this._uid)// 每个组件有相应的_uid
this.show = !this.show;
}
},
data() {
return {
show: false
}
},
template: `<div >
<div class = 'title' @click='change'>{ {title}}</div>
<div v-show='show'>
<slot></slot>
</div>
</div>`
})
let vm = new Vue({
el: '#app',
data: {
},
})
</script>