Search code examples
vue.jsstylesbind

Vue.js bind reactive style object px params


I'm try do reactive change style HTML element from range input, but there is a problem style params font-size, height, width and more with px

<span v-bind:style="myobj.css">Hi all</span>

var vm = new Vue({
    el: '#app', 
    data: {
        myobj: {
            css: {
                color: '#999999',
                fontSize: '18',
            }
        }
    }
})
<input v-model="myobj.css.fontSize" type="range" min="10" max="32" step="1">

but needly - "font-size: 18px, how i can do it? I'm try use filter, but is doesnt work with obj


Solution

  • You could use a computed property for your v-model:

    computed: {
      fontSize: {
        get() {
          const fontPx = /(<?value>\d+(?:\.\d+)?)px/
    
          if (!fontPx.test(newValue))
            return 0
          
          const { groups: { value } } = newValue.match(fontPx)
          return value
        },
        set(newValue) {
          this.myobj.css.fontsize = newValue + 'px'
        }
      }
    }
    

    and in your template:

    <input v-model="fontSize" type="range" min="10" max="32" step="1">
    
    

    EDIT - I just re-read your question. I had the get and set flipped around. The edited answer should do what you need.

    Alternatively, you could use a computed property for the style instead:

    computed: {
      style() {
        const style = { ...this.myobj.css }
        style.fontsize = style.fontsize + 'px'
        
        return style
      }
    }
    
    <span v-bind:style="style">Hi all</span>