![](/img/trans.png)
[英]How to set og:image in Nuxt.js Nuxt/Content blog with images in content folders
[英]nuxt.js - how to set css background image dynamicaly
我使用的是 Nuxt.js,並且有一個自定義組件。
該組件在使用css設置背景圖片的組件中有css。
我嘗試了以下操作,但運行時出現錯誤。 錯誤是:
invalid expression: Invalid regular expression flags in
成分
<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>
我在https://github.com/nuxt/nuxt.js/issues/2123上找到了答案。
基本上,在組件中做:
<div :style="{ backgroundImage: `url(${backgroundUrl})` }">Content with background here</div>
url('~@/assets/autumn-tree.jpg')
我犯了同樣的錯誤,認為這是一個 nuxtjs 問題。 Webpack 使用語法來解析資產。
~ 強制 webpack 將請求視為模塊請求。 然后@從根開始。
<template>
<div>
<div class="backgroundImage" :style="{ backgroundImage: `url(${backgroundImagePath})` }">
</div>
</template>
<script>
import backgroundImagePath from '~/assets/image.jpeg'
export default {
data() {
return { backgroundImagePath }
}
}
</script>
你可以正常寫,但在 '': 'background-image'
v-bind:style="{ 'background-image': 'url(' + api.url + ')' }"
這也是使用 require 和 url 組合來解析資產的另一個示例。
<b-col cols="8" class="hj_projectImage justify-content-center text-center" :style="{backgroundImage: `url(` + require(`~/assets/ProjectPictures/${this.ProjectPicture}`) + `)`}">
</b-col>
總的來說我推薦使用nuxt-image
您可以在那里定義每個分辨率的圖像(媒體查詢)。 使用$img-feature您還可以將其定義為背景圖像:
export default {
computed: {
backgroundStyles() {
const imgUrl = this.$img('https://github.com/nuxt.png', { width: 100 })
return {
backgroundImage: `url('${imgUrl}')`
}
}
}
}
官方文檔已經提供了解決方案,參見: https : //nuxtjs.org/docs/2.x/directory-structure/assets#images
您需要做的就是刪除斜杠:
background-image: url("~assets/autumn-tree.jpg");
對於真正動態的圖像,例如${image}.jpg
:
<img :src="require(`~/assets/img/${image}.jpg`)" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.