简体   繁体   中英

How to use Vue.js variable in style attribute?

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.net/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 ?

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

Read more here: vue website

你应该使用v-bind:style指令

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM