Vue设备侦测(判断设备是移动端还是pc端)

原文地址:存在刷新回到首页的问题

解决如下,在App.vue中增加如下代码


<template>
    <div id="app">
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name: 'app',
        mounted() {
            const isMobile = this.$cookies.get("isMobile");
            window.console.log(isMobile);
            if (isMobile == null) {
                window.console.log("if");
                let is = this._isMobile();
                if (is) {
                    this.$router.replace("/mobile/index").then();
                    this.$cookies.set("isMobile", "1");
                } else {
                    this.$router.replace("/").then();
                    this.$cookies.set("isMobile", "0");
                }
                window.console.log(isMobile);
            } else {
                if (isMobile === "1") {
                    if (!this._isMobile()) {
                        this.$router.replace("/").then();
                        this.$cookies.set("isMobile", "0");
                    }
                } else if (isMobile === "0") {
                    if (this._isMobile()) {
                        this.$router.replace("/mobile/index").then();
                        this.$cookies.set("isMobile", "1");
                    }
                }
            }
        },
        methods: {
            _isMobile() {
                return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
            }
        }
    }
</script>

<style>
    body {
        margin: 0;
    }

    .el-header {
        padding: 0 10%;
    }
</style>

需引入cookies库,

yarn add vue-cookies
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容