滚动动画
$h: 22px;
$h2: $h - 4px;
.hamburger-switch {
height: $h; width: $h * 2; border: none; background: #bfbfbf; border-radius: $h/2; position: relative;
> span {
position: absolute; top: 2px; left: 2px; height: $h2; width: $h2; background: white; border-radius: $h2 / 2; transition: all 250ms;
}
&.hamburger-checked { background: #1890ff;
> span { left: calc(100% - #{$h2} - 2px); } //left: calc(100%),得到其父元素的宽度
}
&:focus { outline: none; }
&:active {
> span { width: $h2 + 4px; }
}
&.hamburger-checked:active {
> span { width: $h2 + 4px; margin-left: -4px; }
}
}
动画由两部分完成。
开始、结束时小圆圈的位置变化通过添加不同类的样式达成。
中间动画效果由 transition属性完成。
如何控制元素CSS类的变化?
<button :class={className : xxx} />当 xxx 为真时,button会被赋予对应的 class 类。
组件状态与父子组件通信
Switch组件的状态不由其本身保持、修改,统统交给父组件维护。
<script lang="ts">
export default {
name:'Switch',
props:{
value:Boolean,
disabled:{
type:Boolean,
default:false
}
},
setup(props,context){
const toggle = ()=>{
context.emit('update:value',!props.value)
}
return {toggle}
}
}
</script>
//Switch组件
<SWitch @update:value="bool = $event" />
<SWitch v-model:value="bool" />
//父组件
Switch组件通过 props来得到父组件传值。在需要修改时通过context.emit通知父组件,第一个参数为注册事件名,事件名需要遵循“update:对应外部属性名称”的格式。第二个参数为新值。
父组件可以通过 @update:value监听对应事件,通过$event拿到新值。可以简化为v-model:value="bool"。