admin管理员组

文章数量:1388225

I need to find a way to use a VueJS variable in a style attribute, as example when I try something like <p style="color:[% randomColor() %];></p> it dissapears on my console.

Here's an example on fiddle : /

HTML :

<div id="app">
    <p style="color:[% randomColor() %];">[% nameAttr() %]</p>
</div>

JavaScript :

var color = new Vue({
    el:'#app',
    methods:{
        nameAttr:function(){
          var name = 'John Doe';
          return name 
        },
        randomColor:function(){
            var font_color = "red";
            return font_color
        }
  },
  delimiters: ["[%","%]"]
});

How can I get around this problem ?

I need to find a way to use a VueJS variable in a style attribute, as example when I try something like <p style="color:[% randomColor() %];></p> it dissapears on my console.

Here's an example on fiddle : https://jsfiddle/Lindow/bjfvdgde/3/

HTML :

<div id="app">
    <p style="color:[% randomColor() %];">[% nameAttr() %]</p>
</div>

JavaScript :

var color = new Vue({
    el:'#app',
    methods:{
        nameAttr:function(){
          var name = 'John Doe';
          return name 
        },
        randomColor:function(){
            var font_color = "red";
            return font_color
        }
  },
  delimiters: ["[%","%]"]
});

How can I get around this problem ?

Share Improve this question asked May 22, 2017 at 8:00 Horai NuriHorai Nuri 5,58817 gold badges84 silver badges136 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4
<div id="app">
  <p :style="{color:randomColor()}">[% nameAttr() %]</p>
</div>

Read more here: vue website

You should use v-bind:style directive

<p v-bind:style="{color:randomColor()}">[% nameAttr() %]</p>

I used the following snippet for setting the background of a div according to the current image.

:style="{'background-image':`url(${currentImg})`}

currentImg can be replaced by any variable name like myVariable

本文标签: javascriptHow to use Vuejs variable in style attributeStack Overflow