Vue--Tab栏切换(父子组件间传值实现)
一、实现原理:
子组件配置props属性接受父组件传来的index值,top子组件采用this.$emit方法传index值给父组件
二、HTML代码:
<div class="box">
<my-top @xxx="fnChange"></my-top>
<my-body :curindex="curindex"></my-body>
</div>
三、CSS代码:
* {
margin: 0;
padding: 0;
}
ul {
list-style-type: none;
}
.box {
width: 400px;
height: 300px;
border: 1px solid #ccc;
margin: 100px auto;
overflow: hidden;
}
.hd {
height: 45px;
}
.hd span {
display: inline-block;
width: 90px;
background-color: pink;
line-height: 45px;
text-align: center;
}
.hd span.current {
background-color: purple;
color: white;
}
.bd li {
height: 255px;
background-color: purple;
display: none;
color: white;
}
.bd li.current {
display: block;
}
四、JS代码:
let vm = new Vue({
el: ".box",
data: {
curindex: 0,
},
methods: {
fnChange(index) {
this.curindex = index;
},
},
components: {
//组件1
"my-top": {
data() {
return {
titleArr: ["体育", "娱乐", "新闻", "综合"],
tempIndex: 0,
};
},
template: `
<div class="hd">
<span @click="change(index)" :class="tempIndex==index?'current':''" v-for='(item,index) in titleArr' :key="item">{{item}}</span>
</div>
`,
methods: {
change(index) {
this.tempIndex = index;
this.$emit("xxx", this.tempIndex);
},
},
},
//组件2
"my-body": {
props: {
curindex: {
default: 0,
},
},
data() {
return {
bodys: [
"我是体育模块",
"我是娱乐模块",
"我是新闻模块",
"我是综合模块",
],
};
},
template: `
<div class="bd">
<ul>
<li :class="curindex==index?'current':''" v-for="(item,index) in bodys" :key="item">{{item}}</li>
</ul>
</div>
`,
},
},
});
五、完整代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style-type: none;
}
.box {
width: 400px;
height: 300px;
border: 1px solid #ccc;
margin: 100px auto;
overflow: hidden;
}
.hd {
height: 45px;
}
.hd span {
display: inline-block;
width: 90px;
background-color: pink;
line-height: 45px;
text-align: center;
}
.hd span.current {
background-color: purple;
color: white;
}
.bd li {
height: 255px;
background-color: purple;
display: none;
color: white;
}
.bd li.current {
display: block;
}
</style>
<script src="./js/vue2.js"></script>
</head>
<body>
<div class="box">
<my-top @xxx="fnChange"></my-top>
<my-body :curindex="curindex"></my-body>
</div>
<script>
let vm = new Vue({
el: ".box",
data: {
curindex: 0,
},
methods: {
fnChange(index) {
this.curindex = index;
},
},
components: {
//组件1
"my-top": {
data() {
return {
titleArr: ["体育", "娱乐", "新闻", "综合"],
tempIndex: 0,
};
},
template: `
<div class="hd">
<span @click="change(index)" :class="tempIndex==index?'current':''" v-for='(item,index) in titleArr' :key="item">{{item}}</span>
</div>
`,
methods: {
change(index) {
this.tempIndex = index;
this.$emit("xxx", this.tempIndex);
},
},
},
//组件2
"my-body": {
props: {
curindex: {
default: 0,
},
},
data() {
return {
bodys: [
"我是体育模块",
"我是娱乐模块",
"我是新闻模块",
"我是综合模块",
],
};
},
template: `
<div class="bd">
<ul>
<li :class="curindex==index?'current':''" v-for="(item,index) in bodys" :key="item">{{item}}</li>
</ul>
</div>
`,
},
},
});
</script>
</body>
</html