圆形组件,通过设置size属性控制圆形的大小且随屏幕自适应

-

最近写一个组件,圆形开关。

在组件封装时被要求通过设置一个size属性来控制圆形的大小。且随屏幕自适应。

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
}
复制代码

 

 

 

 

 

-

posted @   古墩古墩  Views(156)  Comments(0Edit  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2021-06-26 git常用命令总结
2020-06-26 mysql 8.0.20下载与安装、navicat下载、修改mysql密码、连接mysql
2019-06-26 vue-element-admin登录逻辑,以及动态添加路由,显示侧边栏
2019-06-26 vue中用watch监听当前路由
点击右上角即可分享
微信分享提示