Home > Enterprise >  How to assign dynamic variables to CSS content in Vue.js?
How to assign dynamic variables to CSS content in Vue.js?

Time:11-14

Apologies if this shows how much of a novice I am, but I'd like to know more about dynamic variables and CSS in Vue. I'd like to create a system where each time a button is pressed, the letters of the button label become further apart.

Inside a component is it possible to use a counter script such as:

<script>
  export default {
    name: 'Counter', 
    data() {
      return {
        count: 3,
      }
    },
    methods: {
      intrement() {
        this.count  = 1;
      }
    }
  } 
</script>

And then use the count integer value to change CSS text spacing for example? So that in the template, I could use:

<template>
  <header>
    <div>
      <button  style="letter-spacing: `v-bind(count)   ch`;">MYBUTTON</button>
    </div>
  </header>
</template>

I appreciate this is a strange and specific example, but if anyone could give me some feedback as to why this doesn't work, as well as suggestions on how I could achieve this I'd be super appreciative.

CodePudding user response:

In that case, you can directly use the following

<button :style="`letter-spacing: ${count}ch;`">

Here is a playground.

PS: :style is a shorthand for v-bind:style as explained here.


v-bind for CSS (mixing script style) is also a thing.
Here, you're only using script template combo, so an interpolation is enough.

  • Related