简体   繁体   English

Vue(相似)组件和可重用性

[英]Vue (similar) components and reusability

I have a 3 vue components they all do similar stuff. 我有3个Vue组件,它们都做类似的事情。

They all output a square (100px x 100px) div with a value inside it, they are different colours. 它们都输出一个正方形(100px x 100px)div,其中包含一个值,它们是不同的颜色。

  • component 1 (red) takes 2 values and outputs a percentage. 分量1(红色)取2个值并输出一个百分比。

  • component 2 (blue) takes a float value and rounds it up to the next int 组件2(蓝色)采用浮点值并将其舍入到下一个int

  • component 3 (green) takes 3 values and finds the mean. 分量3(绿色)取3个值并找到平均值。

Is there a way to combine this into one reusable component. 有没有一种方法可以将其组合成一个可重用的组件。 They share a template and have similar methods. 他们共享一个模板,并具有类似的方法。

What would be the best way to DRY this up a bit. 什么是将其干燥的最好方法。

It depends on what parts are overlapping. 这取决于哪些部分重叠。 You should likely be individual components, but they can extend a base component if they reuse same template, or they could utilise mixins to share functinality. 您可能应该是单独的组件,但是如果它们重复使用相同的模板,则它们可以扩展基本组件,或者可以利用mixin共享功能。

here is a link that goes into more detail https://alligator.io/vuejs/composing-components/ 这是一个更详细的链接https://alligator.io/vuejs/composed-components/

Extends allow you to extend a single other component, with your component's options taking higher priority over the parent component's. 扩展允许您扩展单个其他组件,而组件的选项比父组件具有更高的优先级。 This means, for example, that if both the parent and your component contain a created() hook, your component's created() hook will be called first, then the parent's. 例如,这意味着,如果父级和组件都包含created()钩子,则将首先调用组件的created()钩子,然后调用父级的。

Mixins are even cooler. Mixins甚至更酷。 They allow you to extend multiple component definitions. 它们使您可以扩展多个组件定义。 Using mixins, it's simple to provide reusable methods and data across any number of your components. 使用mixin,很容易在任意数量的组件中提供可重用的方法和数据。

I should point out though that the use of mixins is controversial. 我应该指出,mixin的使用是有争议的。 The react community has a pretty strong stance https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750 however creating HOCs in vue is a bit trickier react社区的立场很强https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750,但是在Vue中创建HOC有点棘手

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM