方式一:使用transition标签包裹需要过渡动画的标签
<transition name="checkbox"> <van-checkbox v-model='item.flag' v-show="isSign"> <template #icon="props"> <div :class="props.checked ? 'activeIcon' : 'inactiveIcon'"><span></span></div> </template> </van-checkbox> </transition>
对应样式:
.checkbox-enter-active, .checkbox-leave-active { transition: width 0.2s linear; } .checkbox-enter, .checkbox-leave-to { width: 0; } .checkbox-enter-to, .checkbox-leave { width: 28px; }
方式二:(简便)
<van-checkbox v-model='item.flag' v-show='isSign'> <template #icon="props"> <div :class="props.checked ? 'activeIcon' : 'inactiveIcon'"><span></span></div> </template> </van-checkbox>
替换为
<van-checkbox v-model='item.flag' :style="{isSign?'28px':'0px',transition:'width 0.2s linear'}"> <template #icon="props"> <div :class="props.checked ? 'activeIcon' : 'inactiveIcon'"><span></span></div> </template> </van-checkbox>
只需要这样简单的样式,就可以为width变化添加上动画。
对于这种简单动画,这两种方式效果一样,方式二更简单一点,方式一用于更复杂的动画呈现。
vant中CheckBox自定义图标:
官网:
<van-checkbox v-model="checked"> 自定义图标 <template #icon="props"> <img class="img-icon" :src="props.checked ? activeIcon : inactiveIcon" /> </template> </van-checkbox>
export default { data() { return { checked: true, activeIcon: 'https://img01.yzcdn.cn/vant/user-active.png', inactiveIcon: 'https://img01.yzcdn.cn/vant/user-inactive.png', }; }, };
.img-icon { height: 20px; }
效果:
自定义的样式:
<van-checkbox v-model='checked'> 自定义图标 <template #icon="props"> <div :class="props.checked ? 'activeIcon' : 'inactiveIcon'"><span></span></div> </template> </van-checkbox>
// 选中和未选中样式-start .activeIcon { width: 18px; height: 18px; border: 2px solid #198cff; border-radius: 50%; box-sizing: border-box; display: flex; align-items: center; justify-content: center; > span { display: block; width: 10px; height: 10px; background: #198cff; border-radius: 50%; } } .inactiveIcon { width: 18px; height: 18px; border: 2px solid #e0e5f5; border-radius: 50%; box-sizing: border-box; } // 选中和未选中样式-end
效果: