Jade/Pug中更清晰的mixin

3
我希望能够以明确的方式在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故事中实现的,一个PHP实现的pug-->https://sandbox.pug.talesoft.codes/?example=named-mixin-parameters
我想要的是易读的mixin。只要最终结果易于使用,我就不在乎它是如何实现的。
另一个想法是向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 })
1个回答

4
您可以使用一个选项对象来模拟命名参数。您还可以使用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上查看一个实际的例子。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接