如何动态改变background-image

动态改变background-image

最近在开发uni-app小程序时尝试使用栅格布局利用u-grid-item循环遍历元素节点,其中每个元素节点对应的背景图片都不相同,于是就遇到了需要动态改变元素background-image的操作。

错误写法

如果单纯的使用常规的eslint写法。eslint的写法是无法正常显示:

<view :style="{backgroundImage:'url('+listItem.bgpicUrl+')'}">...</view>
list:[
	{
    
    
		title:'模块一',
		ptext:'模块一的描述',
		// 本地图片
		bgpicUrl:'../../static/img/index/组 [email protected]'
	},
]

在网上查了一些说是可以使用js写法,加个转义后的单引号\' ,但是发现会报错

<view :style="{backgroundImage:'url(\'+listItem.bgpicUrl+\')'}">...</view>

正确写法

1. 本地图片

图片路径需要使用require对图片进行导入:

<template>
	<view class="module_content">
	     <u-grid
	       :border="false"
	   	   :customStyle="{padding:3+'%'}"
	        col="2"
	       >
	          <u-grid-item
				   v-for="(listItem,listIndex) in list"
				   :key="listIndex"
				   :customStyle="{padding:10+'rpx'}"
	           >     
				  <view :style="{width:100+'%',padding:10+'rpx',backgroundImage:'url('+listItem.bgpicUrl+')',backgroundSize:'100% 100%' }">
					   <navigator class="nav" :url="listItem.toPageUrl">
							<text class="title" :style="{'color':listItem.Tcolor}" >{
   
   {listItem.title}}</text>
							<text class="ptext" :style="{'color':listItem.Pcolor}">{
   
   {listItem.ptext}}</text>
					   </navigator>
				   </view>
	           </u-grid-item>
	      </u-grid>
	      <u-toast ref="uToast" />			  	
	</view> 
</template>

<script>
	export default {
      
      
		data() {
      
      
			return {
      
      
				list:[
					{
      
      
						title:'模块一',
						ptext:'模块一的描述',
						// 本地图片
						bgpicUrl:require('../../static/img/index/组 [email protected]'),
						toPageUrl:'/pages/webview/mall/index',
						Tcolor:'#4D679B',
						Pcolor:'#76829A'
					},
					{
      
      
						title:'模块二',
						ptext:'模块二的描述',
						bgpicUrl:require('../../static/img/index/组 [email protected]'),
						toPageUrl:"/pages/webview/service/index",
						Tcolor:'#BC5D40',
						Pcolor:'#937A72'
					},
					{
      
      
						title:'模块三',
						ptext:'模块三的描述',
						bgpicUrl:require('../../static/img/index/组 [email protected]'),
						toPageUrl:"/pages/webview/jxkf/index",
						Tcolor:'#4D679B',
						Pcolor:'#99816B'
					},
					{
      
      
						title:'模块四',
						ptext:'模块四的描述',
						bgpicUrl:require('../../static/img/index/组 [email protected]'),
						toPageUrl:"/pages/webview/user/index",
						Tcolor:'#46A589',
						Pcolor:'#73998E'
					},
				]
			}
		},
	}
</script>

2. 网络图片

将图片放置在服务器上,直接请求服务的图片地址:

<view :style="{backgroundImage:'url('+listItem.bgpicUrl+')',backgroundSize:'100% 100%' }">...</view>
list:[
		{
    
    
			title:'模块一',
			ptext:'模块一的描述',
			// 服务器上的图片地址
			bgpicUrl:'http://fuwuqi.com/static/img/index/组 [email protected]'),
			toPageUrl:'/pages/webview/mall/index',
		},
     ]

猜你喜欢

转载自blog.csdn.net/qq_38970408/article/details/132062807