首页 > 其他分享 >[Vue] 高阶组件和套一层父组件的区别

[Vue] 高阶组件和套一层父组件的区别

时间:2024-09-10 16:48:32浏览次数:1  
标签:逻辑 Vue vue 组件 import 高阶 路由

前言

App.vue 的套一层布局组件 MainLayout,MainLayout 做一些统一的布局之外,再做一些子路由相同的逻辑,比如子路由需要权限访问。

但是不灵活,如果一堆路由组件中有一个不需要这个功能,就不能通过父组件嵌套统一逻辑。高阶组件比起套一层父组件复用逻辑更灵活一些。

高阶组件

高阶组件更加关注逻辑的复用,它是一个增强组件的组件,通常通过 tsx/jsx 创建,就是一个函数创建的组件。

不增强组件时不套给组件,侵入性小。

import { defineComponent, onMounted, h } from "vue";

export function withAuth<T>(WrappedComponent: any) {
  return defineComponent({
    name: "withAuth",
    setup(props, { attrs, slots }) {
      return () => h(WrappedComponent);
    }
  });
}
import { withLoading } from "@/components/WithLoading";

const routes = [
  {
    name: "Main",
    path: "/main",
    redirect: "/main/posts",
    component: () => import("@/layouts/Main.vue").then(module => withLoading(module.default))
  }
];

标签:逻辑,Vue,vue,组件,import,高阶,路由
From: https://www.cnblogs.com/Himmelbleu/p/18406702

相关文章