1. 程式人生 > 其它 >從0到1搭建一款頁面自適應元件(Vue.js)

從0到1搭建一款頁面自適應元件(Vue.js)

元件將根據螢幕比例及當前瀏覽器視窗大小,自動進行縮放處理。

建議在元件內使用百分比搭配flex進行佈局,以便於在不同的解析度下得到較為一致的展示效果。
使用前請注意將body的margin設為0,否則會引起計算誤差。

fullScreenContainer.vue

<template>
  <div id="full-screen-container" :ref="ref">
    <template v-if="ready">
      <slot></slot>
    </template>
  </div>
</template>
<script>
import autoResize from './autoResize.js'
export default {
  name: 'DvFullScreenContainer',
  mixins: [autoResize],
  data () {
    return {
      ref: 'full-screen-container',
      allWidth: 0,
      scale: 0,
      datavRoot: '',
      ready: false
    }
  },
  methods: {
    afterAutoResizeMixinInit () {
      const { initConfig, setAppScale } = this
      initConfig()
      setAppScale()
      this.ready = true
    },
    initConfig () {
      const { dom } = this
      const { width, height } = screen
      this.allWidth = width
      dom.style.width = `${width}px`
      dom.style.height = `${height}px`
    },
    setAppScale () {
      const { allWidth, dom } = this
      const currentWidth = document.body.clientWidth
      dom.style.transform = `scale(${currentWidth / allWidth})`
    },
    onResize () {
      const { setAppScale } = this
      setAppScale()
    }
  }
}
</script>
<style lang="scss">
#full-screen-container {
  position: fixed;
  top: 0px;
  left: 0px;

 

更多內容請見原文,原文轉載自:https://blog.csdn.net/weixin_44519496/article/details/118721118