vue3で異なるボタンをクリックして異なるページを切り替える方法

ここに画像の説明を挿入します

上記の要件を完了するには、vue でコンポーネント タグを使用してそれを達成します。コンポーネントは 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