配置全局组件

当组件使用频率较高时,可以将其封装为全局组件

使用方法

在main.ts 引入我们的组件跟随在createApp(App) 后面 切记不能放到mount 后面这是一个链式调用

import { createApp } from 'vue'
import App from './App.vue'
import './assets/css/reset/index.less'
import Card from './components/Card/index.vue'
 
 
createApp(App).component('Card',Card).mount('#app')

// component 函数 第一个参数为组件名称,第二个参数为组件实例

在需使用的vue组件中,直接调用即可,无需另外引入

<template>
 <Card></Card>
</template>

局部组件

前文中父子组件中的子组件,就是父组件的局部组件。 在需使用的vue组件中,需要import后才能使用

递归组件

其实就是,组件在代码中调用自己,形成递归,需要规定调用结束条件

常用的如:侧边栏的菜单组件

<template>
  <div style="margin-left:10px;" class="tree">
    <div :key="index" v-for="(item,index) in data">
      <div @click='clickItem(item)'>{{item.name}}
    </div>
    <TreeItem @on-click='clickItem' v-if='item?.children?.length' :data="item.children" />
  </div>
  </div>
</template>

<script lang="ts">
export default {
  name:"TreeItem" // 本组件的名称,可在template中调用,形成递归
}
</script>

<script setup lang="ts">

type TreeList = {
  name: string;
  icon?: string;
  children?: TreeList[] | [];
};

// 作为子组件时,接收data
type Props<T> = {
  data?: T[] | [];
};
defineProps<Props<TreeList>>();
 
const clickItem = (item: TreeList) => {
  console.log(item)
}

const data = reactive<TreeList[]>([
  {
    name: "no.1",
    children: [   // 传给下一级子组件的值
      {
        name: "no.1-1",
        children: [
          {
            name: "no.1-1-1",
          },
        ],
      },
    ],
  },
  {
    name: "no.2",
    children: [
      {
        name: "no.2-1",
      },
    ],
  },
  {
    name: "no.3",
  },
]);
</script>

Last Updated:
Contributors: haizhiguang