从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;
  overflow: hidden;
  transform-origin: left top;
  z-index: 999;
}
</style>


autoResize.js


export default {
    data() {
        return {
            dom: '',
            width: 0,
            height: 0,
            debounceInitWHFun: '',
            domObserver: ''
        };
    },
    methods: {
        debounce(delay, callback) {
            let lastTime;
            return function() {
                clearTimeout(lastTime);
                const [that, args] = [this, arguments];
                lastTime = setTimeout(() => {
                    callback.apply(that, args);
                }, delay);
            };
        },
        observerDomResize(dom, callback) {
            const MutationObserver =
                window.MutationObserver ||
                window.WebKitMutationObserver ||
                window.MozMutationObserver;
            const observer = new MutationObserver(callback);
            observer.observe(dom, {
                attributes: true,
                attributeFilter: ['style'],
                attributeOldValue: true
            });
            return observer;
        },
        async autoResizeMixinInit() {
            const {
                initWH,
                getDebounceInitWHFun,
                bindDomResizeCallback,
                afterAutoResizeMixinInit
            } = this;
            await initWH(false);
            getDebounceInitWHFun();
            bindDomResizeCallback();
            if (typeof afterAutoResizeMixinInit === 'function')
                afterAutoResizeMixinInit();
        },
        initWH(resize = true) {
            const { $nextTick, $refs, ref, onResize } = this;
            return new Promise(resolve => {
                $nextTick(() => {
                    const dom = (this.dom = $refs[ref]);
                    this.width = dom ? dom.clientWidth : 0;
                    this.height = dom ? dom.clientHeight : 0;
                    if (!dom) {
                        console.warn(
                            'DataV: Failed to get dom node, component rendering may be abnormal!'
                        );
                    } else if (!this.width || !this.height) {
                        console.warn(
                            'DataV: Component width or height is 0px, rendering abnormality may occur!'
                        );
                    }
                    if (typeof onResize === 'function' && resize) onResize();
                    resolve();
                });
            });
        },
        getDebounceInitWHFun() {
            const { initWH } = this;
            this.debounceInitWHFun = this.debounce(100, initWH);
        },
        bindDomResizeCallback() {
            const { dom, debounceInitWHFun } = this;
            this.domObserver = this.observerDomResize(dom, debounceInitWHFun);
            window.addEventListener('resize', debounceInitWHFun);
        },
        unbindDomResizeCallback() {
            let { domObserver, debounceInitWHFun } = this;
            if (!domObserver) return;
            domObserver.disconnect();
            domObserver.takeRecords();
            domObserver = null;
            window.removeEventListener('resize', debounceInitWHFun);
        }
    },
    mounted() {
        const { autoResizeMixinInit } = this;
        autoResizeMixinInit();
    },
    beforeDestroy() {
        const { unbindDomResizeCallback } = this;
        unbindDomResizeCallback();
    }
};


这样,一个页面自适应组件就这样搭建完成了,下面,我们将引入组件看一下效果。


<template>
  <div id="app">
    <fullScreenContainer>
      <img alt="Vue logo" src="./assets/logo.png" />
      <HelloWorld msg="Welcome to Your Vue.js App" />
    </fullScreenContainer>
  </div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
import fullScreenContainer from "./components/fullScreenContainer/fullScreenContainer.vue";
export default {
  name: "App",
  components: {
    HelloWorld,
    fullScreenContainer,
  },
};
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>



微信截图_20220506140947.png


效果很好,这样对于一些开发自适应页面非常容易。

相关文章
|
18天前
|
资源调度 JavaScript API
vue3封装城市联动组件
vue3封装城市联动组件
|
21天前
|
JavaScript 前端开发 开发者
哇塞!Vue.js 与 Web Components 携手,掀起前端组件复用风暴,震撼你的开发世界!
【8月更文挑战第30天】这段内容介绍了Vue.js和Web Components在前端开发中的优势及二者结合的可能性。Vue.js提供高效简洁的组件化开发,单个组件包含模板、脚本和样式,方便构建复杂用户界面。Web Components作为新兴技术标准,利用自定义元素、Shadow DOM等技术创建封装性强的自定义HTML元素,实现跨框架复用。结合二者,不仅增强了Web Components的逻辑和交互功能,还实现了Vue.js组件在不同框架中的复用,提高了开发效率和可维护性。未来前端开发中,这种结合将大有可为。
65 0
|
1天前
|
存储 API
vue3中如何动态自定义创建组件并挂载
vue3中如何动态自定义创建组件并挂载
|
1天前
|
JavaScript
vue 函数化组件
vue 函数化组件
|
18天前
|
存储 JavaScript
vue组件的五种传值方法(父子\兄弟\跨组件)
vue组件的五种传值方法(父子\兄弟\跨组件)
|
6天前
|
JavaScript
Vue组件传值异步问题--子组件拿到数据较慢
Vue组件传值异步问题--子组件拿到数据较慢
10 0
|
19天前
|
Android开发 iOS开发 C#
Xamarin:用C#打造跨平台移动应用的终极利器——从零开始构建你的第一个iOS与Android通用App,体验前所未有的高效与便捷开发之旅
【8月更文挑战第31天】Xamarin 是一个强大的框架,允许开发者使用单一的 C# 代码库构建高性能的原生移动应用,支持 iOS、Android 和 Windows 平台。作为微软的一部分,Xamarin 充分利用了 .NET 框架的强大功能,提供了丰富的 API 和工具集,简化了跨平台移动应用开发。本文通过一个简单的示例应用介绍了如何使用 Xamarin.Forms 快速创建跨平台应用,包括设置开发环境、定义用户界面和实现按钮点击事件处理逻辑。这个示例展示了 Xamarin.Forms 的基本功能,帮助开发者提高开发效率并实现一致的用户体验。
42 0
|
JavaScript
Vue的非父子组件之间传值
全局事件总线 一种组件间通信的方式,适用于任意组件间通信
|
12月前
|
缓存 JavaScript 前端开发
Vue Props、Slot、v-once、非父子组件间的传值....
Vue Props、Slot、v-once、非父子组件间的传值....
72 0
|
JavaScript
Vue中父子组件传值
先在⽗组件中给⼦组件的⾃定义属性绑定⼀个⽗组件的变量