WebReflection / uce-template

A Vue 3 inspired Custom Elements toolless alternative.
https://medium.com/@WebReflection/a-new-web-components-wonder-f9e042785a91
ISC License
108 stars 7 forks source link

How to use properties in the styles section #6

Closed ArthurClemens closed 3 years ago

ArthurClemens commented 3 years ago

I would like to use properties set in the setup function in the styles section. Width, height, colors, etc. And a text string like in this example:

<style>
  img-caption .image-container img {
    position: relative;
  }
  img-caption .image-container img::after {
    content: '{{ caption }}';
  }
</style>

It looks like the variables are not interpolated in the styles section.

WebReflection commented 3 years ago

correct, interpolations are (currently?) valid only for the component definition, and only for its content, not its outer definition.

you can simply define variables within such definition though, and keep CSS clean.

<template is="uce-template">
  <style scoped>
  .image-container::after {
    display: block;
    content: var(--caption, '');
  }
  </style>

  <img-caption>
    <div class="image-container"
         style="{{`--caption:"${caption}"`}}"></div>
  </img-caption>

  <script type="module">
  export default {
    setup() {
      return {caption: 'Hello World'};
    }
  };
  </script>
</template>

codepen example: https://codepen.io/WebReflection/pen/wvzmMMP?editors=1000

WebReflection commented 3 years ago

P.S. as variables are inherited, you can also use the setup(element) approach and set it there directly via element.style.setProperty('--caption', anyValue)

WebReflection commented 3 years ago

P.S.2 alternatively, you can use data-caption='{{caption}}' to simplify escaping cases and use caption: attr(data-caption) ''; instead