Skip to content

自定义组件采用大驼峰命名

  • [[props]]
  • [[事件处理]]
  • [[组件通信#slot 插槽]]

动态组件

动态组件可以通过多个 Tab 切换

html
<!-- currentTab 改变时组件也改变 -->
<component :is="tabs[currentTab]"></component>

component 组件具有一个特殊的 is 属性,可以传入:

  • 被注册的组件名(即注册的全局组件
  • 导入的组件对象
  • 通过一个 ref(例如 let x = ref('div') 来切换原生 HTML 元素,但是一般不这么做) 一般情况下,被切换掉的组件会被卸载,或者使用 KeepAlive 组件包裹被切换掉的组件,以保持组件被切换之前所具有的相应状态。
html
<!-- 非活跃的组件将会被缓存! -->
<KeepAlive>
  <component :is="activeComponent" />
</KeepAlive>

一个 Tab 切换的例子:Vue SFC Playground (vuejs.org)

html
<script>
const currentTab = ref('Home')//当前选中的Tab

const tabs = {
  Home,
  Posts,
  Archive
}
</script>

<template>
  <div class="demo">
    <button
       v-for="(_, tab) in tabs" <!--_是常用索引占位符-->
       :key="tab"
       :class="['tab-button', { active: currentTab === tab }]"  
       <--active类名判断是否选中,匹配CSS样式-->
       @click="currentTab = tab"
     >
      {{ tab }}
    </button>
	  <component :is="tabs[currentTab]" class="tab"></component>
  </div>
</template>