【vue】组件通信案例练习(OptionsAPI方法)

该文章展示了如何在Vue.js中创建一个父组件App.vue和子组件TabControl.vue,通过数据绑定和事件传递实现在点击不同的标签(如衣服、鞋子、裤子)时,切换到相应的列表页面。子组件TabControl接收父组件传递的标题数据,并通过自定义事件向父组件发送点击事件,触发页面内容的更新。
摘要由CSDN通过智能技术生成

案例:

实现点击页面的切换:点击“衣服”,则切换到“衣服列表”;点击“鞋子”,则切换到“鞋子列表”;点击“裤子”,则切换到“裤子页面”。

1.创建App.vue(父组件)和TabControl.vue(子组件)

2.App.vue用于展示TabControl和其对应的页面,TabControl发生了点击则切换到对应页面

3.TabControl.vue用于记录TabControl的点击,并向父组件传递参数

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

//App.vue
<template>
    <div class="app">
      <!-- tab-control页面 -->
      //:titles="['衣服','鞋子','裤子']" :向子组件传值
      //@tabItemClick="tabItemClick":通过v-on监听子组件传递的数据
        <tab-control :titles="['衣服','鞋子','裤子']" @tabItemClick="tabItemClick"/>


        <!-- 展示内容页面 -->
        <h1>{{ pageContents[currentIndex] }}</h1>
    </div>
</template>


<script>
import TabControl from './TabControl.vue';

export default {
//注册一个局部组件TabControl
  components: {
    TabControl
  },

  data() {
    return {
      pageContents: ["衣服列表", "鞋子列表", "裤子列表"],
      currentIndex:0
    }
  },

  methods: {
  //子组件传递的自定义事件
    tabItemClick(index) {
    //将TabControl点击时的index赋值给currentIndex,以便于pageContents[currentIndex]展示页面
      this.currentIndex=index
    }
  }
}

</script>

<style lang="less" scoped>

</style>
//TabControl.vue
<template>
    <div class="tab-control">
      <template v-for="(item,index) in titles" :key="item">
          <div class="tab-control-item"
               //class是动态的,当currentIndex===index为true时,active生效
               :class="{ active: currentIndex===index }"
               //监听itemClick事件
               @click="itemClick(index)">
            <span>{{ item }}</span>
          </div>
      </template>
    </div>
</template>


<script>
export default {
//接受父组件传递的titles数据:使用了props的对象用法
  props: {
    titles: {
      type: Array,
      default:()=>[]
    }
  },

  data() {
    return {
      currentIndex:0
    }
  },

  methods: {
    itemClick(index) {
      //点击titles中的item时,以便active生效
      //例如点击index=1的item时,currentIndex=1,active生效;
      //再点击index=2的item时,currentIndex=1的active失效,currentIndex=2的active生效
      this.currentIndex = index
      //定义一个自定义事件“tabItemClick”,并向父组件传递参数,以便父组件进行页面的切换
      this.$emit("tabItemClick",index)
    }
  }
}
</script>

<style scoped>
.tab-control{
  display: flex;
  height: 44px;
  line-height: 44px;
  text-align: center;
}

.tab-control-item{
  flex: 1;
}

.tab-control-item.active {
    color: red;
    font-weight: 700;
  }

  .tab-control-item.active span {
    border-bottom: 3px solid red;
    padding: 8px;
  }
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱吃炫迈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值