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:list}, 
  {
    
     id: 2, name: '按钮2' ,component:information}, 
  {
    
     id: 3, name: '按钮3' ,component:rule}])
  
// 默认显示的组件页面
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>

猜你喜欢

转载自blog.csdn.net/weixin_56733569/article/details/132762539
今日推荐