Newcomer
Newcomer

Reputation: 503

Vue.js/React/JSX: How to style a tag using a variable in data?

I have a html element textarea_01 to which I want to add a style when I press my button_01 which has an onClick function on it

myFunction: function(event) {
//some code that does something
};

Since I can't use directives with JSX I was thinking that the following will work:

<textarea id="textareaID" style={{resetWidth}}/>

And add to my function that's used on the onClick my code, so it will look like:

myFunction: function(event) {
var textarea = new Vue({
  el: '#textareaID',
  data: {
    resetWidth: 'width: 10px'
  }
})
//some code that does something
};

But it's not working and WebStorm tells me

You are using the runtime-only build of Vue where the template compiler is not available

How do I work around this and accomplish what I want to do, which is add a css property to a html element after I click on another element ?

Note: Webpack and the followin is used in the code github.com/vuejs/babel-plugin-transform-vue-jsx Note that almost all built-in Vue directives are not supported when using JSX, the sole exception being v-show, which can be used with the v-show={value} syntax.

Upvotes: 0

Views: 916

Answers (1)

Gerard Reches
Gerard Reches

Reputation: 3154

You have to bind the style attribute to Vue, because you can't use moustaches on tag properties:

<textarea id="textareaID" :style="resetWidth" />

Because you are using runtime only Vue version, you should try with another approach.

Remove the moustaches from the textarea:

<textarea id="textareaID" />

Set the styles for the element with javascript on the mounted hook or another lifecycle hook that you want:

myFunction: function(event) {
    var textarea = new Vue({
        el: '#textareaID',
        data: {
            resetWidth: 'width: 10px'
        },
        mounted: function () {
            this.$el.setAttribute("style", this.resetWidth);
        },
    })
    //some code that does something
};

Upvotes: 3

Related Questions