vue.js 引用背景图 background 无效的3种解决办法

#vue.js项目中,出现css调用background背景图无效?如何解决?

或者调用<img>标签,也无效果? 直接上代码,自行对比查找一下:


1. 正确的代码,示例如下:

<template>
  <div class="demo">
    <!-- 成功引入的三种方法: -->
    <!-- 图1 -->
    <div class="img1"></div>
    <!-- 图2 -->
    <div class="img2" :style="{backgroundImage: url( + bg2 + ) }"></div>
    <!-- 图3 -->
    <img src="~@/../static/images/logo3.png" width="100">
  </div>
</template>

<script>
import Bg2 from @/../static/images/logo2.png

export default {
          
   
	name: App,
	data () {
          
   
	    return {
          
   
			bg2: Bg2,
	    }
	}
}
</script>

<style>
	.demo{
          
   width: 100px;margin: 50px auto;}
	.img1{
          
   
	    width: 100px;
		height: 100px;
	    background: url(~@/../static/images/logo1.png) center center no-repeat;
	    background-size: 100px auto;
	}
	.img2{
          
   
		width: 100px;
	    height: 100px;
	    background-position: center center;
	    background-repeat:  no-repeat;
	    background-size: 100px auto;
	}
</style>

上述代码中,出现了诸如:~@/和 @/,如果删除后,测试效果也正常,你也可以都去掉,不影响。
报错结果截图如下:
修改为正确代码方法,类比如下:
<div :style="{
             
      backgroundImage: url(https://cn.vuejs.org/images/logo.png), width: 400px, height: 400px}">foo</div>
具体参考官方文档:

相比其他方法:

如果你用了vue-cli脚手架,在build/utils.js中找到ExtractTextPlugin位置在对象中加入这句publicPath: ../../就行了(本人未测试)。



以上就是关于“vue.js 引用背景图 background 无效的3种解决办法”的简单介绍。
经验分享 程序员 微信小程序 职场和发展