size属性要求是数字,我们把它的单位当成px。要做到随屏幕自适应,需要转换为其它的单位
以下列出3中方法:
方法1:将size转换成vw (最简单有效)
方法2:将size转换为rem (需要额外监听屏幕宽度)
方法3:将size转换成百分比 (高度通过padding-top撑起)
<template>
<span :class="switchClass"></span>
</template>
<script>
import { computed, defineComponent, ref } from 'vue'
export default defineComponent({
name: 'CircleSwitch',
props: {
size: {
type: Number,
default: 26
}
},
setup(props) {
const switchClass = computed(() => {
return [
'circle_switch',
]
});
// 监听窗口宽度变化
const windowWIdth = ref(document.body.clientWidth);
const listenResize = () => {
window.onresize = () => {
windowWIdth.value = document.body.clientWidth;
}
}
listenResize();
const theme = computed(() => {
return {
// size: `${props.size / document.body.clientWidth * 100}vw` // 方法1
// size: `${props.size / (14 * 1920 / windowWIdth.value)}rem` // 方法2
size: `${props.size / document.body.clientWidth * 100}%` // 方法3
}
})
return {
switchClass,
theme
}
},
})
</script>
<style lang="scss" scoped>
.circle_switch{
display: inline-block;
border: 1px solid red;
width: v-bind('theme.size');
height: v-bind('theme.size'); 方法1、方法2
// padding-top: v-bind('theme.size'); 方法3
}