javascript nuxt.js - 如何动态设置 css 背景图片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48436017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nuxt.js - how to set css background image dynamicaly
提问by Magick
Im using Nuxt.js, and have a custom component.
我使用 Nuxt.js,并有一个自定义组件。
This component has css in the component that sets a background image using css.
该组件在使用 css 设置背景图像的组件中具有 css。
I've tried the following but I get an error when I run this. The error is:
我尝试了以下操作,但在运行时出现错误。错误是:
invalid expression: Invalid regular expression flags in
Component
零件
<template>
<section class="bg-img hero is-mobile header-image" v-bind:style="{ backgroundImage: 'url(' + image + ')' }">
<div class="">
<div class="hero-body">
<div class="container">
<h1 class="title">
{{ result }}
</h1>
<h2 class="subtitle ">
Hero subtitle
</h2>
</div>
</div>
</div>
</section>
</template>
<script>
export default {
props: ['result', 'image']
}
</script>
<style>
.bg-img {
background-image: url(~/assets/autumn-tree.jpg);
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
background-color: #999;
}
</style>
采纳答案by Magick
I found the answer on https://github.com/nuxt/nuxt.js/issues/2123.
我在https://github.com/nuxt/nuxt.js/issues/2123上找到了答案。
Basically, in the component do:
基本上,在组件中做:
<div :style="{ backgroundImage: `url(${backgroundUrl})` }">Content with background here</div>
回答by Quickee
url('~@/assets/autumn-tree.jpg')
url('~@/assets/autumn-tree.jpg')
I made the same mistake thinking this was a nuxtjs problem. Webpack uses syntax to resolve assets.
我犯了同样的错误,认为这是一个 nuxtjs 问题。Webpack 使用语法来解析资产。
~ enforces webpack to treat the request as a module request. And then @ start at root.
~ 强制 webpack 将请求视为模块请求。然后@从根开始。
回答by KitKit
You can write it normally but in '': 'background-image'
你可以正常写,但在 '': 'background-image'
v-bind:style="{ 'background-image': 'url(' + api.url + ')' }"

