col.vue 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <template>
  2. <div class="zai-col" :style="styleVal">
  3. <slot />
  4. </div>
  5. </template>
  6. <script setup>
  7. import {getCurrentInstance, onMounted, ref, watch} from "vue";
  8. const props = defineProps({
  9. span: { //栅格占据的列数,1-24
  10. type: [Number, String],
  11. default: 24,
  12. },
  13. })
  14. //获取父组件实例
  15. const parent = getCurrentInstance().parent
  16. //渲染完成
  17. onMounted(() => {
  18. setStyleValue(props.span)
  19. })
  20. //监听
  21. watch(() => [
  22. props.span,
  23. ], ([span]) => {
  24. setStyleValue(span)
  25. })
  26. //设置样式
  27. const styleVal = ref({})
  28. const setStyleValue = (span) => {
  29. if (parent?.type?.name === 'HcRow') {
  30. //处理栅格间隔
  31. const gutter = Number(parent?.props?.gutter ?? 0)
  32. if (gutter !== 0) {
  33. const num = Math.floor(gutter / 2) + (gutter % 2) + 'px'
  34. styleVal.value['--zai-row-padding'] = num ? num : '0'
  35. }
  36. //计算栅栏宽度
  37. const width = (1 / 24) * Number(span) * 100
  38. styleVal.value['--zai-col-width'] = `${width}%`
  39. styleVal.value['--zai-col-flex'] = `0 0 ${width}%`
  40. }
  41. }
  42. </script>
  43. <style scoped lang="scss">
  44. @import "./style.scss";
  45. </style>