高阶组件( hoc )是 react 生态系统的常用词汇, react 中代码复用的主要方式就是使用高阶组件,并且这也是官方推荐的做法。而 vue 中复用代码的主要方式是使用 mixins ,并且在 vue 中很少提到高阶组件的概念,这是因为在 vue 中实现高阶组件并不像 react 中那样简单,原因在于 react 和 vue 的设计思想不同,但并不是说在 vue 中就不能使用高阶组件,只不过在 vue 中使用高阶组件所带来的收益相对于 mixins 并没有质的变化。本篇文章主要从技术性的角度阐述 vue 高阶组件的实现,且会从 react 与 vue 两者的角度进行分析。
从 react 说起
起初 react 也是使用 mixins 来完成代码复用的,比如为了避免组件不必要的重复渲染我们可以在组件中混入 purerendermixin :
const purerendermixin = require('react-addons-pure-render-mixin') const mycomponent = react.createclass({ mixins: [purerendermixin] })
后来 react 抛弃了这种方式,进而使用 shallowcompare :
const shallowcompare = require('react-addons-shallow-compare') const button = react.createclass({ shouldcomponentupdate: function(nextprops, nextstate) { return shallowcompare(this, nextprops, nextstate); } })
这需要你自己在组件中实现 shouldcomponentupdate 方法,只不过这个方法具体的工作由 shallowcompare 帮你完成,即浅比较。
再后来 react 为了避免开发者在组件中总是要写这样一段同样的代码,进而推荐使用 react.purecomponent ,总之 react 在一步步的脱离 mixins ,他们认为 mixins 在 react 生态系统中并不是一种好的模式(注意:并没有说 mixins 不好,仅仅针对 react 生态系统),观点如下:
1、 mixins 带来了隐式依赖
2、 mixins 与 mixins 之间, mixins 与组件之间容易导致命名冲突
3、由于 mixins 是侵入式的,它改变了原组件,所以修改 mixins 等于修改原组件,随着需求的增长 mixins 将变得复杂,导致滚雪球的复杂性。
具体大家可以查看这篇文章 mixins considered harmful 。不过 hoc 也并不是银弹,它自然带来了它的问题,其观点是: 使用普通组件配合 render prop 可以做任何 hoc 能做的事情 。
本篇文章不会过多讨论 mixins 和 hoc 谁好谁坏,就像技术本身就没有好坏之分,只有适合不适合。难道 react 和 vue 这俩哥们儿不也是这样吗
以上就是vue高阶组件的使用方法的详细内容。
