问题描述:
v-for里面的组件呢,我要根据不同的item配置不同的style,于是有了这样的写法
<template><view class="weeks-item" v-for="(day,dayIndex) in item" :key="dayIndex"><view :style="bgStyle(day)" >{{ day. extraInfo.info}}</view></view>
</template>
<script>export default{computed:{bgStyle:function(){return (day)=>{if(day.extraInfo){return `background-color:${day.extraInfo.data.bgColor}`}else{return ''}}}}}
</script>
然后一运行 ,就给报错
👉🏻 ☞ 解决办法:
<template><view class="uni-calendar__weeks-item" v-for="(day,dayIndex) in styledItems(item)" :key="dayIndex"><view class="daylayer-custom"><view :style="day.dynamicStyle" >{{ day. extraInfo.info}}</view></view></view>
</template>
<script>export default{computed:{styledItems:function(){return (item)=>{return item.map(day => ({...day,dynamicStyle: this.getDynamicStyle(day)}));}}},methods: {getDynamicStyle(day) {if(day.extraInfo){return `background-color:${day.extraInfo.data.bgColor}`}return ''},}}
</script>
这样,就可以了,主要修改思路就是把style作为day元素的一个属性,然后动态style绑定这个属性即可。
小感悟:写代码不要太固执,打不过就加入,主打一个曲线救国。