2

有什么建议如何根据参数存在创建条件 mixin?例如,我需要验证是否传递了所有参数以执行某些操作,例如:

.margin (@margintop:0,@marginbottom:0,@marginright:0,@marginleft:0) {

  // if @marginright:0 or @marginleft:0 are passed do that...

  // else...

}
4

1 回答 1

6

1:

通常,当您需要为传递的不同数量的参数生成不同的东西时,您根本不需要使用默认参数值,例如:

.margin(@top, @bottom, @right, @left) {
    /* right and left are passed */
}

.margin(@top, @bottom) {
    /* right and left are not passed */
}

.margin() {
    /* no arguments passed */
}

// etc.

请注意,这些混入中的每一个都可以重用其他混入,例如.margin(@top, @bottom)可以为“无左右情况”做一些特殊的事情,然后调用.margin(@top, @bottom, 0, 0)以执行主要工作。

2:

但是如果由于某种原因您仍然需要这些默认值,您可以使用一些不能是有效边距的特殊默认值,例如:

.margin(@top: undefined, @bottom: undefined, @right: undefined, @left: undefined) {
    .test-args();

    .test-args() when (@right = undefined) {
        /* right is not passed */
    }
    .test-args() when (@left = undefined) {
        /* left is not passed */
    }

    .test-args()
        when not(@right = undefined)
        and  not(@left  = undefined) {
            /* right and left are passed */
    }

    // etc.
}

3:

第三种选择是使用可变参数并测试它们的计数,但我猜这个是最冗长和愚蠢的:

.margin(@args...) {
    .eval-args(length(@args));  // requires LESS 1.5.+
    .eval-args(@nargs) {
        // default values:
        @top:    not passed;
        @bottom: not passed;
        @right:  not passed;
        @left:   not passed;
    }
    .eval-args(@nargs) when (@nargs > 0) {
        @top:    extract(@args, 1);
    }
    .eval-args(@nargs) when (@nargs > 1) {
        @bottom: extract(@args, 2);
    }
    .eval-args(@nargs) when (@nargs > 2) {
        @right:  extract(@args, 3);
    }
    .eval-args(@nargs) when (@nargs > 3) {
        @left:   extract(@args, 4);
    }

    args: @top, @bottom, @right, @left;
}

尽管它在某些特殊用例中可能有其优点。

于 2013-11-27T11:10:05.323 回答