2023.11.10 | admin | 71次围观
**
前言
uni-app开发小程序油时候兼容性真的是千奇百怪
今天自己封装了一个无信息占位组件,组件源代码如下:
第一个问题请看注释
<template>
<view class="no-tips flex-c-c">
<image :src="imgSrc" :style="[imgStyle]"></image>
//这里的imgStyle传过来的是一个对象,如果是这样用:
//
//H5生效,小程序不生效,查看调试器,渲染的是这样的:style=[object,Object],
//套上数组括号[]就解决这个问题了
<text>{{tipsWord}}</text>
</view>
</template>
<script>
export default{
props:{
imgStyle:{
type:Object,
defualt:{}
},
tipsWord:{
type:String,
defualt:'暂无数据'
},
imgSrc:{
type:String,
defualt:'../static/img/common/no_tips.png'
}
},
data(){
return{
}
},
}
</script>
<style lang="less" scoped>
.no-tips{
height: 60vh;
image{
width:300rpx ;
height: 300rpx;
}
}
</style>
组件引用并传值:
//我已经全局挂载了组件,无需引入
<noTips
tipsWord='暂无收藏'
:imgSrc="require('../../static/img/userCenter/icon_nocollect.png')"
:imgStyle="{width:'280rpx',height:'232rpx'}"
></noTips>
第二个问题子组件获取图片路径问题
传入图片的途径在H5端和小程序端不一样;
微信小程序端是根据组件的的目录来,H5是根据引用组件的目录来
一开始我这样用导致了两端不兼容:
:imgSrc="'../../static/img/userCenter/icon_nocollect.png'"
调试器查看路径:
h5:'../../static/img/common/no_tips.png'
微信小程序:'../static/img/common/no_tips.png'
导致了两端只有一端能显示
然后改成这样就行了:
:imgSrc="require('../../static/img/userCenter/icon_nocollect.png')"
有时候觉得是坑,其实是我们没有好好去看官方文档;
以下是uni-app官方说法: uni-app官网说明:Class 与 Style 绑定
Class 与 Style 绑定
为节约性能,我们将 Class 与 Style 的表达式通过 compiler 硬编码到 uni-app 中,支持语法和转换效果如下:
class 支持的语法:
<view :class="{ active: isActive }">111</view>
<view class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }">222</view>
<view class="static" :class="[activeClass, errorClass]">333</view>
<view class="static" v-bind:class="[isActive ? activeClass : '', errorClass]">444</view>
<view class="static" v-bind:class="[{ active: isActive }, errorClass]">555</view>
style 支持的语法:
<view v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">666</view>
<view v-bind:style="[{ color: activeColor, fontSize: fontSize + 'px' }]">777</view>
非H5端不支持 Vue官方文档:Class 与 Style 绑定 中的 classObject 和 styleObject 语法。
不支持示例:
<template>
<view :class="[activeClass]" :style="[baseStyles,overridingStyles]"></view>
</template>
<script>
export default {
data() {
return {
activeClass: {
'active': true,
'text-danger': false
},
baseStyles: {
color: 'green',
fontSize: '30px'
},
overridingStyles: {
'font-weight': 'bold'
}
}
}
}
</script>
注意:以:style=""这样的方式设置px像素值微信小程序组件传值,其值为实际像素微信小程序组件传值,不会被编译器转换。
此外还可以用 computed 方法生成 class 或者 style 字符串,插入到页面中,举例说明:
<template>
<!-- 支持 -->
<view class="container" :class="computedClassStr"></view>
<view class="container" :class="{active: isActive}"></view>
<!-- 不支持 -->
<view class="container" :class="computedClassObject"></view>
</template>
<script>
export default {
data () {
return {
isActive: true
}
},
computed: {
computedClassStr () {
return this.isActive ? 'active' : ''
},
computedClassObject () {
return { active: this.isActive }
}
}
}
</script>
用在组件上
非H5端(非自定义组件编译模式)暂不支持在自定义组件上使用 Class 与 Style 绑定
以上!
版权声明
本文仅代表作者观点。
本文系作者授权发表,未经许可,不得转载。
发表评论