首页 > 解决方案 > Vue.js 无法从方法中添加样式

问题描述

我想从方法中将一些样式添加到 html 元素中:

<div class="add-profile-img" v-bind:style="getBackgroundImg()">

方法是:

getBackgroundImg: function() {
return {   
    width: 180px; 
    height: 180px; 
    background-color: 'yellow';
    background-image:url(this.BASE_URL +'/uploads/noimg.gif');
    }
},

但是,我得到

Syntax Error:   Identifier directly after number (79:13)

  77 |      getBackgroundImg: function() {
  78 |          return {   
> 79 |          width: 180px; 
     |                    ^

我该如何解决?

标签: javascriptvue.js

解决方案


以像素为单位的维度需要采用字符串格式,以便函数返回有效的 javascript 对象:

return {   
    width: '180px', 
    height: '180px',
    'background-color': 'yellow',
    'background-image': `url(${this.BASE_URL}/uploads/noimg.gif)`
}

推荐阅读