How to switch to different pages by clicking different buttons in vue3

Insert image description here

To complete the above requirements, we can use the component tag in vue to achieve it. Component is a special tag in Vue.js, used to dynamically bind other components. It can be used with the v-bind:is directive to decide which component to render. Below is the sample code

<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>

Guess you like

Origin blog.csdn.net/weixin_56733569/article/details/132762539