欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue動態(tài)組件之:is在組件中的使用場景

 更新時間:2023年07月07日 10:54:01   作者:seekHelp  
這篇文章主要介紹了vue動態(tài)組件之:is在組件中的使用場景,本文結(jié)合示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

vue動態(tài)組件之:is在組件中的使用

使用場景:

有些場景會需要在兩個組件間來回切換,比如 Tab 界面:
我們可以通過 Vue 的<component> 元素和特殊的 is attribute 實現(xiàn)的:如

<!-- currentTab 改變時組件也改變 -->
<component :is="currentTab"></component>

在上面的例子中,被傳給:is的值可以是以下幾種:

  • 被注冊的組件名
  • 導入的組件對象
    你也可以使用 isattribute 來創(chuàng)建一般的 HTML 元素。

當使用 <component :is="...">來在多個組件間作切換時,被切換掉的組件會被卸載。我們可以通過 <KeepAlive> 組件強制被切換掉的組件仍然保持“存活”的狀態(tài)。

vue3中的:is 動態(tài)組件

1、注意事項

1、在Vue2 的時候is是通過組件名稱切換的,在Vue3 setup是通過組件實例切換的

2、如果直接把組件實例放到reactive中代理,vue會發(fā)出警告。告知我們可以通過shallowRef 或者 markRaw 跳過proxy 代理。因為組件實例進行響應(yīng)式代理毫無意義,且浪費性能

在這里插入圖片描述

2、:is 動態(tài)組件使用

子組件通過defineProps接受傳參

<template>
  <div class="content">
    <div class="tabs" v-for="item in tabArr" :key="item.name" @click="tabChange(item.comName)">
      {{ item.name }}
    </div>
  </div>
  <component :is="currentCom"></component>
</template>
<script setup lang="ts">
  import { ref, reactive, markRaw } from 'vue'
  import A from './A.vue'
  import B from './B.vue'
  import C from './C.vue'
  type Tab = {
    name: string,
    comName: any
  }
  // 從復(fù)雜數(shù)據(jù)類型中取出自己想要的幾個屬性
  type Com = Pick<Tab, 'comName'>
  const tabArr = reactive<Tab[]>([
    {
      name: 'A組件',
      comName: markRaw(A)
    },
    {
      name: 'B組件',
      comName: markRaw(B)
    },
    {
      name: 'C組件',
      comName: markRaw(C)
    },
  ])
  const currentCom = ref<Com>(tabArr[0].comName)
  const tabChange = (item: Com) => {
    currentCom.value = item
  }
</script>
<style>
  .content {
    display: flex;
    padding: 20px;
    height: 40px;
    width: 100vw;
    background: #f1f1f1;
  }
  .tabs {
    width: 100px;
    height: 40px;
    background: #ffffff;
    margin-right: 5px;
    border: 1px solid #000;
  }
</style>

到此這篇關(guān)于vue - 動態(tài)組件(:is在組件中的使用)的文章就介紹到這了,更多相關(guān)vue動態(tài)組件:is內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論