tab页案例(Vue组件传值)

父子组件之间如何进行通信呢?
  • 父组件传递给子组件:通过props属性
  • 子组件传递给父组件:通过$emit触发事件

1.父组件

<template>
  <div>
    <hello-world :titles="titles" @titleClick="titleClick"></hello-world>
    <div class="contents">{{contents[currentIndex]}}</div>
  </div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
  components: {
    HelloWorld
  },
  data() {
    return {
      titles: ["衣服", "鞋子", "裤子"],
      contents: ["衣服页面", "鞋子页面", "裤子页面"],
      currentIndex: 0
    };
  },
  methods: {
    titleClick(index) {
      this.currentIndex = index;
    }
  }
};
</script>

<style scoped>
.contents {
  margin: 50px 20px;
}
</style>

2.子组件


<template>
  <div class="tab">
    <div
      class="item"
      v-for="(item,index) in titles"
      :key="index"
      @click="titleClick(index)"
      :class="{active:currentIndex===index}"
    >
      <span>{{item}}</span>
    </div>
  </div>
</template>
<script>
export default {
  emits: ["titleClick"],
  props: {
    titles: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      currentIndex: 0
    };
  },
  methods: {
    titleClick(index) {
      this.currentIndex = index;
      this.$emit("titleClick", index);
    }
  }
};
</script>

<style scoped>
.tab {
  display: flex;
  margin-top: 50px;
}
.item {
  flex: 1;
  text-align: center;
  font-size: 30px;
}
.active span {
  color: red;
  border-bottom: 3px solid red;
  padding: 5px 10px;
}
</style>

/*coderwhy老师Vue3+TS学习笔记*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值