2024-1-18
直接看实例,在实际开发中,<view class="photo" :style="playerImg">,这里用v-bind方式绑定了js方法,通过method或者computed中定义如
playerImg() {
return {
height: '800rpx',
position: 'relative',
backgroundImage: `url(${this.playerInfo.img_url})`,
backgroundSize: 'cover'
};
之后,在uniapp的内置浏览器中,调用是正常的。但! 不管是微信小程序浏览器还是实机,都无法正确展示图片,又或是说,无法识别图片路径。
通过改变方法,将组件样式改为内嵌式,
这里我先后使用了{{ }}语法和`${}`插值语法,都未有明确效果。
1、<view class="选手照片" :style="`height: 800rpx; position: relative; background-image: url('${playerInfo.img_url}'); background-size: cover;`"></view>
2、<view class="photo" style="height: 800rpx; position: relative; background-size: cover; background-image: url('{{ playerInfo.img_url }}')"></view>
其中,标号2方法报错:
15:26:12.766 Module Error (from ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/templateLoader.js):
15:26:12.767 (Emitted value instead of an instance of Error)
15:26:12.800 Errors compiling template:
15:26:12.800 style="height: 800rpx; position: relative; background-size: cover; background-image: url('{{ playerInfo.img_url }}')": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div style="{{ val }}">, use <div :style="val">.
15:26:12.821 40 | </view>
15:26:12.835 41 | </view>
15:26:12.836 42 | <view class="photo" style="height: 800rpx; position: relative; background-size: cover; background-image: url('{{ playerInfo.img_url }}')">
15:26:12.852 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
15:26:12.861 43 | <view class="label" style="position: absolute; bottom: 0; right: 0; display: flex">
15:26:12.973 44 | <view v-if="playerInfo.PartyMember" class="" style="margin: 10rpx">
15:26:12.974 at E:\tangren-buildingItems\tr-voteSystem\pages\vote_detail\vote_detail.vue:0
经过查阅发现,
错误提示显示你在模板中使用了插值语法 {{ }}
在样式属性中,而这是不被允许的。在 Vue 模板中,样式属性的绑定应该使用 v-bind
或其缩写形式 :
。
修改代码,将样式属性的插值改为绑定语法:
<view class="photo" :style="'height: 800rpx; position: relative; background-size: cover; background-image: url(' + playerInfo.img_url + ')'"></view>
成功。路径获取正确。