#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="~@/assets/img/pageBg.png" width="100"></div>
</template><script>
import Bg2 from '@/assets/img/pageBg.png'export default {name: 'App',data () {return {bg2: Bg2,或者:bg2: require('@/assets/img/pageBg.png')}}
}
</script><style>.demo{width: 100px;margin: 50px auto;}.img1{width: 100px;height: 100px;background: url('~@/assets/img/pageBg.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>
上述代码中,出现了诸如:
~@/
和@/
,如果删除后,测试效果也正常,你也可以都去掉,不影响。
2. 错误的代码,截图对比,如下:
报错结果截图如下:
修改为正确代码方法,类比如下:
<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种解决办法”的简单介绍。