Vue.js 数据绑定样式背景图像不起作用 [英] Vue.js data-bind style backgroundImage not working

查看:79
本文介绍了Vue.js 数据绑定样式背景图像不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像的 src 绑定到元素中,但它似乎不起作用.我收到无效的表达式.生成的函数体:{ backgroundImage:{ url(image) }".

I'm trying to bind the src of an image in an element, but it doesn't seem to work. I'm getting an "Invalid expression. Generated function body: { backgroundImage:{ url(image) }".

文档 说要使用Kebab-case"' 或 'camel-case'.

The documentation says to use either 'Kebab-case' or 'camel-case'.

<div class="circular" v-bind:style="{ backgroundImage: { url(image) }"></div>

这里有一个小提琴:https://jsfiddle.net/0dw9923f/2/

推荐答案

问题是 backgroundImage 的值需要是这样的字符串:

The issue is that the value for backgroundImage needs to be a string like this:

<div class="circular" v-bind:style="{ backgroundImage: 'url(' + image + ')' }"></div>

这是一个有效的简化小提琴:https://jsfiddle.net/89af0se9/1/

Here's a simplified fiddle that's working: https://jsfiddle.net/89af0se9/1/

回复:下面关于烤肉串的评论,这是你可以做到的:

Re: the comment below about kebab-case, this is how you can do that:

<div class="circular" v-bind:style="{ 'background-image': 'url(' + image + ')' }"></div>

换句话说,v-bind:style 的值只是一个普通的 Javascript 对象,并且遵循相同的规则.

In other words, the value for v-bind:style is just a plain Javascript object and follows the same rules.

更新:关于为什么您可能无法使其正常工作的另一条说明.

UPDATE: One other note about why you may have trouble getting this to work.

您应该确保您的 image 值被引用,以便最终结果字符串是:

You should make sure your image value is quoted so that the end resulting string is:

url('some/url/path/to/image.jpeg')

否则,如果您的图片 URL 中包含特殊字符(例如空格或括号),浏览器可能无法正确应用它.在 Javascript 中,赋值看起来像:

Otherwise, if your image URL has special characters in it (such as whitespace or parentheses) the browser may not apply it properly. In Javascript, the assignment would look like:

this.image = "'some/url/path/to/image.jpeg'"

this.image = "'" + myUrl + "'"

从技术上讲,这可以在模板中完成,但是为了保持有效的 HTML 而进行的转义是不值得的.

Technically, this could be done in the template, but the escaping required to keep it valid HTML isn't worth it.

更多信息在这里:是否真的引用了 url() 的值有必要吗?

这篇关于Vue.js 数据绑定样式背景图像不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆