组件化开发之父子组件之间通信练习,商品页面的切换

最终实现

image

SFC文件

app组件

点击查看代码
<template>
    <tab-control :titles='titles' @tabClick="hundleTabClick"></tab-control>
    <h2>{{contents[currentIndex]}}</h2>
</template>

<script>
    import tabControl from "./components/TabControl.vue"
    export default {
        components:{
            tabControl
        },
        data(){
            return {
                titles:['衣服','鞋子','裤子'],
                contents:["衣服页面","鞋子页面","裤子页面"],
                currentIndex:0,
            }
        },
        methods:{
            hundleTabClick(index){
                this.currentIndex = index;
            }
        }
    }
</script>

<style scoped>

</style>

tabControl组件

点击查看代码
<template>
    <div class="tabControl-container">
        <div class="tabControl-item" :class="{active:currentIndex == index}" @click="itemClick(index)"  v-for="(title,index) in titles" :key="title">
            <span>{{ title }}</span>
        </div>
    </div>
</template>

<script>
    export default {
        emits:['tabClick'],
        props:{
            titles:{
                type:Array,
                require:true,
                default:["这里是默认值1","这里是默认值2","这里是默认值3"],
            }
        },
        data(){
            return {
                currentIndex:0,
            }
        },
        methods:{
            itemClick(index){
                this.currentIndex = index;
                console.log("tab被点击了!!");
                this.$emit("tabClick",index);
            }
        },
    }
</script>

<style scoped>
.tabControl-container{
    display: flex;
}
.tabControl-item{
    flex-grow: 1;
    flex-shrink: 1;
    text-align: center;
    /* height: 10vh; */
}
.tabControl-item span{
    border-bottom: 1vh solid orangered;
    padding: 1vh 2vh;
}
.active{
    color: orangered;
}
</style>

mian.js

点击查看代码
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

html

点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>商品页面的切换</title>
</head>
<body>
  <div id="app"></div>
</body>
</html>
posted @ 2021-12-01 17:44  睡成蛆  阅读(63)  评论(0编辑  收藏  举报