使用Mixins还是Extends
Mixins
Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.
Extends
Extending Vue Components for Cleaner Code
This pattern works best for features that have similar core logic (often with complicated functions and data manipulation) with distinct differences in implementation. This could include vastly different markup or templates, as long as they share functionality. The component that extends a base component can either inherit the entire template from the base or create its own. There is no way to append or prepend markup to the base template.
怎样选择
相同点在于,Mixins、Extends、Vuex 三种方式都可以在组件间进行数据的复用。
不同点在于:
- Mixins:是复用小块的代码到已有的组件中
- Extends:通过extend已有组件,添加/修改一些options得到新的组件
场景1
假定在项目中,有页面即被PC端使用,也被H5端使用,但是数据逻辑(data和moethods)基本一致的。
分析:共有的部分显然不属于“小块代码”,因此使用Extends更合理。
场景2
待补充