vue3中如何实现通过点击不同的按钮切换不同的页面

在这里插入图片描述

完成以上需求,我们可以使用vue中的component标签来实现。 component是Vue.js中一个特殊的标签,用于动态地绑定其它组件。它可以与v-bind:is指令一起使用,来决定要渲染哪个组件。下面是示例代码

<template>
  <div class="app-content">
  <!-- 这里是页面切换按钮区 -->
    <div>
      <div class="flex flex-wrap gap-10">
        <el-button class="un-active" type="primary" 
        :class="{ 'active': selectedBtn == item.id }"
         v-for="item in topBtn"
         :key="item.id" 
         @click="selectChange(item)">
         {{ item.name }}
         </el-button>
      </div>
      
    </div>
    <!-- 这里是页面展示区 -->
    <div>
    <component :is="selectedComponent"></component>
    </div>
  </div>
</template>

<script setup name="ecological">
import { computed, getCurrentInstance, reactive, ref, onMounted } from 'vue';
import A from './A.vue' // 导入组件A
import B from './B.vue' // 导入组件B
import C from './C.vue' // 导入组件C

const { proxy } = getCurrentInstance();
// 当前选中按钮
const selectedBtn = ref(null);
// 按钮列表
const topBtn = ref([
  { id: 1, name: '按钮1' ,component:A}, 
  { id: 2, name: '按钮2' ,component:B}, 
  { id: 3, name: '按钮3' ,component:C}])
  
// 默认显示的组件页面
const selectedComponent= ref(A);

// 点击按钮切换事件
const selectChange = (item) => {
  selectedBtn.value = item.id; 
  selectedComponent.value = item.component; 
}

onMounted(() => {
  selectedBtn.value = topBtn.value[0].id;
})
</script>

<style lang="scss" scoped>
:deep() {
  .el-button {
    margin-left: 0px;
  }

  .un-active {
    background: #DEEAFF;
    border-color: #DEEAFF;
    color: black;
  }

  .active {
    background: #042ca4;
    border-color: #042ca4;
    color: #ffffff;
  }
}
</style>

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值