VUE---选项卡

273 阅读1分钟
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
  * {
        margin: 0;
        padding: 0;
        list-style-type: none;
    }

    .content {
       
        display: flex;
        flex-direction: column;
        border: 1px solid red;
        height: 300px;
        width: 500px;
    }

    .title {
        display: flex;
        
    }

    .title>div {
        flex: 1;
        text-align: center;
        padding: 10px;
    }

    .title>div.active {
        background: red;
        color: #fff;
    }
</style>
</head>

<body>
<div id="app">
  
      <wb>
          <ib label='火车票'>火车票outBaroutBaroutBaroutBaroutBar</ib>
          <ib label='火车票'>火似懂非懂是车票outBaroutBaroutBaroutBaroutBar</ib>
          <ib label='火车票'>火车地方大幅度票outBaroutBaroutBaroutBaroutBar</ib>
          <ib label='火车票'>火水电费第三方车票outBaroutBaroutBaroutBaroutBar</ib>
      </wb>
  
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    Vue.component('wb', {
        mounted() {
            this.$children[0].show=true //默认第一条显示
        },
        data(){
            return{
              activeIndex:0,
              titles:[]
            }
        },
        watch: {
            activeIndex(val){//父组件里面的点击i和activeIndex传值 
                this.$children.forEach((r,i)=>{//根据父组件的下标 选取被调用父组件的子组件 把子组件循环 如果传入的父组件的下标和子组件的下标相同 也就是父组件的val和子组件的i相同 那么当前父组件的子组件就显示 否则隐藏
                    if(val===i){//更改的是子组件的show的状态
                        this.$children[i].show=true
                    }else{
                        this.$children[i].show=false
                    }
                })
            }
        },
        template:`
        <div class='content'> 
            <div class='title'>
                <div @click='activeIndex=i' :class='{active:activeIndex===i}'
                v-for='item,i in titles'
                >
                {{item}}
            </div>
            </div>
            <slot></slot>
        </div>
        
        `//放在了wb中
        //表头点击谁 谁高亮 
        //titles是从子组件传过来的label的值    item就是在label中直接写的文字  反向传递给父组件 文字先赋值给label 再用$parent把每一个label传递给titles item就是label中的每一个元素  点击谁 谁就显示 谁显示那么就获取他身上的label
        //子组件所穿插的地方
    })

    Vue.component('ib', {
        props:['label'],//传入数据
        created() {
            this.$parent.titles.push(//用$parent把每一个label传递给titles
                this.label
            )
        },
        data(){
            return{
                show:false//定义show的状态
            }
        },
        template:`
        <div v-show='show'><slot></slot></div>
        `//子组件中v-show控制显示 slot插入文本
    })
   new Vue({
       el:'#app',
       data(){
           return{
             
           }
       },
       
   })
</script>
</body>

</html>