Skip to content

[vue] 你了解什么是高阶组件吗?可否举个例子说明下? #332

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
haizhilin2013 opened this issue Jun 20, 2019 · 3 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

[vue] 你了解什么是高阶组件吗?可否举个例子说明下?

@haizhilin2013 haizhilin2013 added the vue vue label Jun 20, 2019
@xunbie
Copy link

xunbie commented Jul 19, 2019

https://blog.csdn.net/z609373067/article/details/81258966

@sc950828
Copy link

一个方法,接收一个组件返回一个新组件

@Cai-zhiji
Copy link

高阶组件

高阶组件(Higher-Order Component,HOC)是一种在Vue中常用的设计模式,用于复用组件逻辑和增强组件功能。它是一个函数,接受一个组件作为参数,并返回一个新的组件。

HOC的主要作用是封装和包装组件,通过将通用的逻辑提取到HOC中,可以使组件更加简洁、可维护和可复用。下面是一个简单的例子来说明高阶组件的使用:

// 定义一个高阶组件
const withLogging = (WrappedComponent) => {
  return {
    created() {
      console.log(`Component '${WrappedComponent.name}' created.`);
    },
    destroyed() {
      console.log(`Component '${WrappedComponent.name}' destroyed.`);
    },
    render(h) {
      return h(WrappedComponent, this.$slots.default);
    },
  };
};

// 定义一个普通组件
const MyComponent = {
  template: `
    <div>
      <h1>Hello, World!</h1>
    </div>
  `,
};

// 使用高阶组件包装普通组件
const MyEnhancedComponent = withLogging(MyComponent);

// 在应用中使用增强后的组件
new Vue({
  render: (h) => h(MyEnhancedComponent),
}).$mount("#app");

在上面的例子中,withLogging是一个高阶组件,它接受一个组件作为参数并返回一个新的组件。在这个例子中,高阶组件增加了对组件的创建和销毁的日志记录功能,并将原始组件包装在一个新的组件中。

通过使用高阶组件,我们可以在不改变原始组件的情况下,通过简单的函数调用来增加组件的功能。这种模式使得代码更加可维护和可复用,并提供了一种灵活的方式来扩展组件的行为。

需要注意的是,高阶组件是一个纯函数,它不会修改原始组件的行为,而是通过包装和增强原始组件来创建一个新的组件。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
vue vue
Projects
None yet
Development

No branches or pull requests

4 participants