Does Svelte facilitate dynamic CSS styling?

耗尽温柔 提交于 2019-12-05 06:58:05

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>

There's no inbuilt way to do use, eg, conditionals {#if} inside class=, per other popular frameworks.

Since inline expressions will become unweildy as soon as you have more than two classes, I'd go stright to helpers in that case. Quick example of a class builder helper:

helpers: {
    getSlideClasses(index, currentIndex) {
        let classes = ['js_slide']
        if ( index === currentIndex ) {
            classes.push('selected')
        }
        if ( index === 0 ) {
            classes.push('first')
        }
        return classes.join(' ')
    }
}

And then:

<div class='{ getSlideClasses(index, currentIndex)}'>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!