1. 程式人生 > >vue踩坑系列——backgroundImage路徑問題

vue踩坑系列——backgroundImage路徑問題

在前端開發中,background-image屬性非常常見,有很多時候需要使用內聯樣式來繫結此屬性,但是在vue-cli專案中,如果如下面程式碼填寫路徑會找不到圖片

<script type="text/javascript">
	import TemplateNav from './TemplateNav'

	export default {
		name: 'FooterNav',
		components: {
			'TemplateNav': TemplateNav
		},
		data() {
			return {
				//使用相對路徑會找不到圖片
				shouye:'url(../../assets/images/shouye/index2x.png)',
				fenlei:'url(../../assets/images/shouye/fenlei2x.png)',
				search:'url(../../assets/images/shouye/search2x.png)',
				shopcart:'url(../../assets/images/shouye/gouwuche2x.png)',
				mine:'url(../../assets/images/shouye/I2x.png)'
			}
		},
		props: {
			num: {
				default: '0'
			}
		},
	}
</script>


正確的路徑應該如下面這樣

data() {
	return {
		shouye:'url(' + require('../../assets/images/shouye/index2x.png') + ')',
		fenlei:'url(' + require('../../assets/images/shouye/fenlei2x.png') + ')',
		search:'url(' + require('../../assets/images/shouye/search2x.png') + ')',
		shopcart:'url(' + require('../../assets/images/shouye/gouwuche2x.png') + ')',
		mine:'url(' + require('../../assets/images/shouye/I2x.png') + ')'
	}
},

使用require()方法,require()是node.js方法