Svelte 是否有助于动态 CSS 样式? [英] Does Svelte facilitate dynamic CSS styling?

查看:58
本文介绍了Svelte 是否有助于动态 CSS 样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Svelte 中,应如何根据组件状态更改元素上的类?

In Svelte, how should classes be changed on elements depending upon component state?

例如,您可能希望在特定条件下将类应用于按钮,如下例所示.

For instance, you may wish to apply a class to a button under certain conditions, as in the following example.

<button class="{{class}}">

现在,这可以通过创建一个返回类名的计算属性来实现,或空字符串,在某些条件下.

Right now, this can be achieved by creating a computed property which would return class names, or empty strings, under certain conditions.

但是,我担心这是否会污染计算属性命名空间.例如,如果有一个 status,可能需要同时设置一个动态文本,如 statusMessage,和一个类,如 statusClass.

However, I am concerned over whether this might be polluting the computed properties namespace. For instance, if there were a status, it might be desired to both set a dynamic text, like statusMessage, and a class, like statusClass.

有没有更好的方法来做到这一点,或者计算属性是要走的路?是否计划为 Svelte 提供更明确的 CSS 支持?

Is there a better way to do this, or are computed properties the way to go? Is any more explicit support for CSS planned for Svelte?

推荐答案

您可以使用内联表达式,如下所示:

You can use an inline expression, like so:

<button class='{{active ? "active": "inactive"}}'>
  {{active ? 'Selected' : 'Select this'}}
</button>

这通常比使用计算属性要好,因为只需查看模板就可以立即清楚可能的值是什么.

That's generally better than using a computed property, because it's immediately clear what the possible values are just by looking at the template.

您也可以使用辅助函数,如果表达式会变得笨拙——在某些情况下,您可能更喜欢使用辅助函数而不是计算值:

You can also use helper functions, if the expression would become unwieldy — in some situations you might prefer these to computed values:

<button class='{{getClass(status)}}'>{{getText(status)}}</button>

<script>
  export default {
    helpers: {
      getClass(status) {
        // ...
      },
      getText(status) {
        // ...
      }
    }
  };
</script>

这篇关于Svelte 是否有助于动态 CSS 样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆