编程语言
首页 > 编程语言> > javascript-Jade / Pug中更清晰的mixins

javascript-Jade / Pug中更清晰的mixins

作者:互联网

我正在寻找在Jade / Pug中显式显示mixin参数的方法.

这是一些伪代码来说明我的意思:

// Current situation
+c-button('Button label', 'overstated', 'large')

// Here we can see what the mixin expects
+c-button(btnLabel: 'Button label', btnType: 'overstated', btnSize: 'large')

这样,mixin公开了“ API”.这使得那些不了解代码内部所有技巧的人可以复制/可粘贴/可修改的代码.

(我发现这实际上是在pug的故事中实现的,pug是PHP的pug实现-> https://sandbox.pug.talesoft.codes/?example=named-mixin-parameters)

我追求的是清晰的mixin.只要最终结果易于使用,我都不会在意它的实现方式.

另一个想法是将单个选项对象添加到混合.

现在,我编写的这段代码根本不起作用.寻找一个Javascript专家来给您一些启发:)

mixin c-button({options})
    - { 
         [
           option1: true
         ]
      }
    a.c-button(href="#") #{btnLabel}

// Code does not actually work because mixins can't take objects?
+c-button({ option1: false })

解决方法:

您可以使用选项对象模拟命名参数.您还可以使用Object.assign()将选项与预定义的选项对象合并以模拟选项默认值:

mixin button (options)
  - var DEFAULT_OPTIONS = { type: 'button', variant: 'default' };
  - options = Object.assign({}, DEFAULT_OPTIONS, options || {});
  button(class='btn--' + options.variant, type=options.type)= options.label

+button({ label: 'foo' })

请参阅https://codepen.io/thomastuts/pen/JNVWYX的工作示例.

标签:pug,mixins,javascript
来源: https://codeday.me/bug/20191026/1932780.html