Vue常用组件

一、轮播图

1、在components——> swiper里创建三个文件,文件如下:
注:他们三个直接复制粘贴过去使用就好。
1)Swiper.vue

<template>
    <div id="hy-swiper">
        <div class="swiper" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
            <slot></slot>
        </div>
        <slot name="indicator">
        </slot>
        <div class="indicator">
            <slot name="indicator" v-if="showIndicator && slideCount>1">
                <div v-for="(item, index) in slideCount" class="indi-item" :class="{active: index === currentIndex-1}" :key="index"></div>
            </slot>
        </div>
    </div>
</template>

<script>
export default {
    name: "Swiper",
    props: {
        interval: {
            type: Number,
            default: 3000
        },
        animDuration: {
            type: Number,
            default: 300
        },
        moveRatio: {
            type: Number,
            default: 0.25
        },
        showIndicator: {
            type: Boolean,
            default: true
        }
    },
    data: function () {
        return {
            slideCount: 0, // 元素个数
            totalWidth: 0, // swiper的宽度
            swiperStyle: {}, // swiper样式
            currentIndex: 1, // 当前的index
            scrolling: false, // 是否正在滚动
        }
    },
    mounted: function () {
        // 1.操作DOM, 在前后添加Slide
        setTimeout(() => {
            this.handleDom();

            // 2.开启定时器
            this.startTimer();
        }, 3000)
    },
    methods: {
        /**
     * 定时器操作
     */
        startTimer: function () {
            this.playTimer = window.setInterval(() => {
                this.currentIndex++;
                this.scrollContent(-this.currentIndex * this.totalWidth);
            }, this.interval)
        },
        stopTimer: function () {
            window.clearInterval(this.playTimer);
        },

        /**
         * 滚动到正确的位置
         */
        scrollContent: function (currentPosition) {
            // 0.设置正在滚动
            this.scrolling = true;

            // 1.开始滚动动画
            this.swiperStyle.transition = 'transform ' + this.animDuration + 'ms';
            this.setTransform(currentPosition);

            // 2.判断滚动到的位置
            this.checkPosition();

            // 4.滚动完成
            this.scrolling = false
        },

        /**
         * 校验正确的位置
         */
        checkPosition: function () {
            window.setTimeout(() => {
                // 1.校验正确的位置
                this.swiperStyle.transition = '0ms';
                if (this.currentIndex >= this.slideCount + 1) {
                    this.currentIndex = 1;
                    this.setTransform(-this.currentIndex * this.totalWidth);
                } else if (this.currentIndex <= 0) {
                    this.currentIndex = this.slideCount;
                    this.setTransform(-this.currentIndex * this.totalWidth);
                }

                // 2.结束移动后的回调
                this.$emit('transitionEnd', this.currentIndex - 1);
            }, this.animDuration)
        },

        /**
         * 设置滚动的位置
         */
        setTransform: function (position) {
            this.swiperStyle.transform = `translate3d(${position}px, 0, 0)`;
            this.swiperStyle['-webkit-transform'] = `translate3d(${position}px), 0, 0`;
            this.swiperStyle['-ms-transform'] = `translate3d(${position}px), 0, 0`;
        },

        /**
         * 操作DOM, 在DOM前后添加Slide
         */
        handleDom: function () {
            // 1.获取要操作的元素
            let swiperEl = document.querySelector('.swiper');
            let slidesEls = swiperEl.getElementsByClassName('slide');

            // 2.保存个数
            this.slideCount = slidesEls.length;

            // 3.如果大于1个, 那么在前后分别添加一个slide
            if (this.slideCount > 1) {
                let cloneFirst = slidesEls[0].cloneNode(true);
                let cloneLast = slidesEls[this.slideCount - 1].cloneNode(true);
                swiperEl.insertBefore(cloneLast, slidesEls[0]);
                swiperEl.appendChild(cloneFirst);
                this.totalWidth = swiperEl.offsetWidth;
                this.swiperStyle = swiperEl.style;
            }

            // 4.让swiper元素, 显示第一个(目前是显示前面添加的最后一个元素)
            this.setTransform(-this.totalWidth);
        },

        /**
         * 拖动事件的处理
         */
        touchStart: function (e) {
            // 1.如果正在滚动, 不可以拖动
            if (this.scrolling) return;

            // 2.停止定时器
            this.stopTimer();

            // 3.保存开始滚动的位置
            this.startX = e.touches[0].pageX;
        },

        touchMove: function (e) {
            // 1.计算出用户拖动的距离
            this.currentX = e.touches[0].pageX;
            this.distance = this.currentX - this.startX;
            let currentPosition = -this.currentIndex * this.totalWidth;
            let moveDistance = this.distance + currentPosition;

            // 2.设置当前的位置
            this.setTransform(moveDistance);
        },

        touchEnd: function (e) {
            // 1.获取移动的距离
            let currentMove = Math.abs(this.distance);

            // 2.判断最终的距离
            if (this.distance === 0) {
                return
            } else if (this.distance > 0 && currentMove > this.totalWidth * this.moveRatio) { // 右边移动超过0.5
                this.currentIndex--
            } else if (this.distance < 0 && currentMove > this.totalWidth * this.moveRatio) { // 向左移动超过0.5
                this.currentIndex++
            }

            // 3.移动到正确的位置
            this.scrollContent(-this.currentIndex * this.totalWidth);

            // 4.移动完成后重新开启定时器
            this.startTimer();
        },

        /**
         * 控制上一个, 下一个
         */
        previous: function () {
            this.changeItem(-1);
        },

        next: function () {
            this.changeItem(1);
        },

        changeItem: function (num) {
            // 1.移除定时器
            this.stopTimer();

            // 2.修改index和位置
            this.currentIndex += num;
            this.scrollContent(-this.currentIndex * this.totalWidth);

            // 3.添加定时器
            this.startTimer();
        }
    }
}
</script>

<style scoped>
#hy-swiper {
    overflow: hidden;
    position: relative;
}

.swiper {
    display: flex;
}

.indicator {
    display: flex;
    justify-content: center;
    position: absolute;
    width: 100%;
    bottom: 8px;
}

.indi-item {
    box-sizing: border-box;
    width: 8px;
    height: 8px;
    border-radius: 4px;
    background-color: #fff;
    line-height: 8px;
    text-align: center;
    font-size: 12px;
    margin: 0 5px;
}

.indi-item.active {
    background-color: rgba(212, 62, 46, 1);
}
</style>

2)SwiperItem.vue
注:在这使用槽口,在使用轮播图的时候,插入内容

<template>
    <div class="slide">
      <slot></slot>
    </div>
</template>

<script>
	export default {
		name: "Slide"
	}
</script>

<style scoped>
  .slide {
    width: 100%;
    flex-shrink: 0;
  }

  .slide img {
    width: 100%;
  }
</style>

3)index.js
注:这块这样写,方便组件的调用

import Swiper from './Swiper'
import SwiperItem from './SwiperItem'

export {
  Swiper, SwiperItem
}

2、使用

<template>
    <div>
        <h1>首页</h1>
        <div class="i-box">
            <Swiper>
            <!--正这进行便利-->
                <Swiper-item v-for="(item,index) in banner" :key="index">
                    <!-- 因为轮播图可以添砖 -->
                    <a :href="item.跳转地址">
                        <img :src="item.图片名" alt="">
                    </a>
                </Swiper-item>
            </Swiper>
        </div>
    </div>
</template>
<script>
// 1、在首页里,我们只需要面向home.js去发送网络请求,所以在这杨引用
import {homeObtain} from '../api/home';
// 这里写的原因是在index里已经给他暴露了
import {Swiper, SwiperItem} from '@/components/common/swiper/index'
export default {
    data() {
        return {
            banner:[]//这里是轮播图在包含的数据
        }
    },
    components:{
        Swiper,
        SwiperItem
    },
  
  /*注:1、函数里面的所有东西都是局部变量,当这个函数执行完,所有变量都会被内存回收掉
       2、函数调用 ——》他是压入到函数栈中的(保存函数嗲用过程中的所有变量)
       3、函数调用结束——》他会弹出函数栈(弹出之后,他会释放所有变量,所有变量就会垃圾回收掉;
       如果你在调用一次,南无它就会 重新创建这些变量,函数调用结束,它又会消失)
       */
}
</script>
<style scoped>
   
</style>

二、Tabs

1、对Tabs进行封装
注:在src——》components——》Tabs.vue

<template>
    <div class="tab_control">
        <div v-for="(item,index) in tab" :key="index" class="tab_control_item"
        :class="{active: index===currentIndex }"
        @click="fun(index)"
        >
            <span>{{item}}</span>
        </div>
    </div>
</template>
<script>
export default {
    name:'Tabs',
    // 在这接收从父传过来的数据,即tab的内容
    props:{
        tab:{
            type:Array,
            default(){
                return []
            }
        }
    },
    // 在data里记录一下,选中的状态
    data() {
        return {
            // 用它记录(为了给上面动态添加class名)
            currentIndex:0
        }
    },
    methods: {
        // 把上面的index拿到,然后传进来,再去改变currentIndex
        fun(num){
            this.currentIndex=num;
            // 把这个数据传到父元素
            this.$emit('tabFun',num);
        }
    },
}
</script>
<style scoped>
    .tab_control{
        display: flex;
        /* 设置样式 */
        font-size:.16rem;
        height:.4rem;
        line-height:.4rem;
    }
    .tab_control_item{
        flex:1;
        text-align: center;
    }
    /* 这块添加选中时候的样式 */
    .active{
        color: pink;
    }
</style>

2、在页面中调用
注:在src——》pages——》Index.vue

<template>
    <div class="home-box">
        <Tabs :tab="['流行','新款','精选']" class="tab_top" @tabFun="tabfun" />
    <!-- 根据Tabs传过来的index,设置不同的字符串,然后传值给展示组件,响应的数据 -->
        <!-- <GoodList :goodaSsembly="goods[currentType].list" /> -->
        <GoodList :goodaSsembly="goods[currentType].list" />
    </div>
</template>
<script>
// 在这调用组件
import Tabs from '@/components/tabs/Tabs';
import GoodList from '@/components/GoodsList';

export default {
    data() {
        return {
            goods:{//page 是当前页数,list是数据
            // 默认只请求第一页的数据
                // 流行
                'pop':{page:0,list:[]},
                // 新款
                'new':{page:0,list:[]},
                // 精选
                'sell':{page:0,list:[]}
            },
            // 给这快写一个默认数据类型
            currentType:'pop'
        }
    },
    components:{
        Tabs,
        GoodList
    },
    // 2、在页面加载完成之后,组件立即调用
    created() {
/*

    这块写的是一些数据请求
*/
        
    },
    // 在这写一个计算属性,否侧上面的那个就太长了
    computed: {
        showTabs(){
            return this.goods[this.currentType].list;
        }
    },
    
    // 在方法里面 才是具体要做的事情
    methods: {
        /*
        *下面是事件监听
        */
        tabfun(index){
            // 更具这块传过来的数据,去取到数据
            console.log(index);
            
            switch(index){
                case 0:
                    this.currentType = 'pop';
                    break;
                case 1:
                    this.currentType = 'new';
                    break;
                case 2:
                    this.currentType = 'sell';
                    break;//最后一个写不写break都行
            }
        },
    },
}
</script>
<style scoped>
   /* 让他滚动到一定程度,停止滚动,保持在那个位置 */
   .tab_top{
       position:sticky;
       top:.44rem;
   }
</style>

3、创建数据展示的组件
注:scr——》components——》show在这个里面创建两个组件,一个是商品列表的组件,令一个是商品列表展示样式的组件
1)列表组件

<template>
    <div class="goods-item">
        <!-- 在这遍历一共有多少个Item ,在把item传递给样式组件-->
        <GoodsItem v-for="(item,index) in goodaSsembly" :key='index' :goodsItem="item"/>
    </div>
</template>
<script>
//商品列表展示样式
import GoodsItem from './GoodsItem';
export default {
    name:'GoodsList',
    props:{
       goodaSsembly:{
           type:Array,
           default(){
               return []
           }
       } 
    },
    components:{
        GoodsItem
    }
}
</script>
<style scoped>

</style>

2)样式组件

<template>
    <div class="">
        <img :src="goodsItem.图片" alt="">
        <p>{{goodsItem.商品标题}}</p>
        <p>{{goodsItem.商品价格}}</p>
    </div>
</template>
<script>
export default {
    props:{
        goodsItem:{
            type:Object,
            default(){
                return {}
            }
        }
    }
}
</script>
<style scoped>

</style>

三、对时间戳 进行展示

1、在vue遍历的时候使用,在div里面使用函数

<template>
    <div>
        <div v-for="(item,index) in time" :key="index">
            <p>{{dateFormat(item.faultTime)}}</p>
        </div>
    </div>
</template>
<script>
export default {
	data(){
		return {
			time:[1586828879897,1586412552094,1586828879897]
		}
	},
    methods: {
        // 时间戳,转普通格式
        dateFormat:function(time) {
            var date=new Date(time);
            var year=date.getFullYear();
            /* 在日期格式中,月份是从0开始的,因此要加0
            * 使用三元表达式在小于10的前面加0,以达到格式统一  如 09:11:05
            * */
            var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
            var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
            var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
            var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
            var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
            // 拼接
            return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
        }
    },
}
</script>
<style lang="stylus" scoped>

</style>

2、封装起来
①在src——>utils——>Time.js
注:在使用的时候,直接复制粘贴

export function formatDate(date, fmt) {
    // 1、获取年份
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    // 2、获取
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),//在这进行修改H(24小时制)和h(12小时制)
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
};
//保证用做一个补贴,确保时间有两位
function padLeftZero (str) {
    return ('00' + str).substr(str.length);
};

②使用

<template>
    <div>
        {{showData}}
    </div>
</template>
<script>
import {formatDate} from '@/utils/Time.js'
export default {
    data() {
        return {
            // 这个是后端给的时间戳
            time:1535694719
        }
    },
    //计算属性(也可在别地方写)
    computed:{
        showData(){
            // 将事件戳转为对象
            const date = new Date(this.time*1000);
            //将data进行格式化
            return formatDate(date,'yyyy-MM-dd hh:mm:ss');
        }
    },
}
</script>
<style scoped>

</style>

在这里插入图片描述

四、postcss-px-to-viewport移动端适配

注:从像素单位生成视口单位(vw,vh,vmin,vmax)。
1、下载
npm install postcss-px-to-viewport --save-dev
2、使用
postcss.config.js进行修改

module.exports = {
  plugins: {
    autoprefixer: {},
    'postcss-px-to-viewport': {
      viewportWidth: 750,   /* 视窗的宽度,对应的是我们设计稿的宽度,
      一般是750*/
      viewportHeight: 1334, /* 视窗的高度,根据750设备的宽度来指定,
      一般指定1334,也可以不配置*/
      unitPrecision:5,     // 指定`px`转换为视窗单位值的小数位数
      viewportUnit: "vw",   //指定需要转换成的视窗单位,建议使用vw
      selectorBlackList: ['.ignore'],/* 指定不转换为视窗单位的类,可以自定
      义,可以无限添加,建议定义一至两个通用的类名,尽量不要添加太多*/
      minPixelValue: 1,     /* 小于或等于`1px`不转换为视窗单位,
      你也可以设置为你想要的值*/
      mediaQuery: false     // 允许在媒体查询中转换`px`
      //exclude:
    }
  }
}
/*
1、在js中使用正则:/正则相关的规则/
2、exclude中存放的元素必须是正则表达式
注:如果值为regexp(正则),将忽略匹配文件(即这个文件不去转换)。
3、按照排序文件写对应的正则

4、正则的规则:
1)^abc : 表示匹配的内容必须以什么开头(以abc开头)
2)abc$ :表示匹配的内容必须以什么结尾(以abc结尾) 
*/

3、这下写样式的时候,就可以用px了。

五、在子父组件中使用对方的方法和变量(即data里的数据)

1、在组件中使用子组件的方法和变量(即data里的数据)

1)父组件

<template>
    <div>
    	<!-- 通过ref拿到 -->
        <Son ref="Son"></Son>
        <button @click="funa()">点击</button>
    </div>
</template>
<script>
import Son from '@/components/Son.vue';
export default {
    components:{
        Son
    },
    methods: {
        funa(){
            this.$refs.Son.fun();
            console.log(++this.$refs.Son.num);
        }
    },
}
</script>

2)子组件

<template>
    <div>
        {{num}}
    </div>
</template>
<script>
export default {
    data() {
        return {
            num:'0'
        }
    },
    methods: {
        fun(){
            console.log('我是子');
        }
    },
}
</script>

2、在组件中使用父组件的方法和变量(即data里的数据)

1)子组件

<template>
    <div>
        <button @click="fun()">点击</button>
    </div>
</template>
<script>
export default {
    methods: {
        fun(){
            this.$parent.funa();
            // 修改数据
            ++ this.$parent.num;
        }
    },
}
</script>

2)父组件

<template>
    <div>
        {{num}}
        <!-- 子组件 -->
        <Son></Son>
    </div>
</template>
<script>
import Son from '@/components/Son.vue';
export default {
    components:{
        Son
    },
    data() {
        return {
            num:0
        }
    },
    methods: {
        funa(){
            console.log('我是父');
        }
    },
}
</script>

六、遍历Object对象

Object.keys传入对象可以取得索引
1、forEach的应用

let faultTypeInfo = {"过流故障": 195, "速断故障": 606, "接地故障": 678, "瞬时接地故障": 159};
let Info = [];//console.log([ { "value": 195, "name": "过流故障" }, { "value": 606, "name": "速断故障" }, { "value": 678, "name": "接地故障" }, { "value": 159, "name": "瞬时接地故障" } ])
Object.keys(faultTypeInfo).forEach((item) =>{
	Info.push(
		{value:faultTypeInfo[item],name:item}
	)
});

2、map的方法

var data={a:1,b:2,c:9,d:4,e:5};
console.log(Object.keys(data));//["a", "b", "c", "d", "e"]
Object.keys(data).map((key,item)=>{
	console.log(key,data[key]);//key=>属性名    data[key]=>属性值
});

:Object.keys的案例
1)传入字符串,返回索引

var str = 'ab1234';
console.log(Object.keys(obj));  //[0,1,2,3,4,5]

2)传入数组 返回索引

var arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // console: ["0", "1", "2"]

七、字符串截取

1、保留前面的

let obj = "你好!世界";
console.log(obj.match(/(\S*)!/)[1]);//你好

2、保留后面的

let obj = "你好!世界";
console.log(obj..match(/!(\S*)/)[1]);//世界

八、vue中引入高德地图

1、在public——>index.html里引入
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=cb6152d432c370a781b4b2a80a84e9a6"></script>
住:这个在高德官网里复制。
2、然后在vue.config.js里面配置一下,否则会报错,报AMap未定义。

module.exports = {
    configureWebpack: {
        externals: {
            AMap: "window.AMap"
        }
    }
};

3、使用
住:各种需要看文档
下面已在地图上标点为例。

<template>
    <div>
        <div style="width: 100vw;height: 100vh" id="container"></div>
    </div>
</template>
<script>
//引用AMap
import AMap from "AMap";
export default {
    data() {
        return {
           
        };
    },
    created() {
       this.Map_call();
    },
    methods: {
        Map_call(){
            this.$nextTick(()=>{
                this.structure();
            })
        },
        // 构建地图,并且设置中心点
        structure(){
        	let map = new AMap.Map("faultMap", {
                resizeEnable: true,
                center:[116.368904, 39.923423],//地图中心点
                zooms: [1, 16],
                zoom: 12
            });
            /**
             * @description:下面是坐标转换,gps转高德
             * @param {type} 
             * @return {type} 
             */
            AMap.convertFrom([116.368904, 39.923423], 'gps', function (status, result) {
                if (result.info === 'ok') {
                    let marker = new AMap.Marker({
                        position:[116.368904, 39.923423],
                        map: map,
                        icon:"http://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
                    });
                    marker.content = `aaaaa`;
                    marker.on('click', markerClick);
                    map.setMarker;
                }
            });
            var infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(8, -30) });
            function markerClick(e) {
                infoWindow.setContent(e.target.content);
                infoWindow.open(map, e.target.getPosition());
            }
            map.setFitView();
        }
    },
    mounted() {
        
    }
};
</script>
<style scoped>
</style>

在这里插入图片描述

注:使用zoom API无用。

九、时间转换

1、获取当天一天的时间

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
</body>
</html>
<script>
    // 获取当天00:00点的时间戳
    let time=  Date.parse(new Date(new Date(new Date().toLocaleDateString()).getTime()));
    console.log(time);
    let date = new Date(time);
    console.log(date);


    // 获取当天最后一秒的时间戳 23:59:59
    let end_time = Date.parse(new Date(new Date(new Date().toLocaleDateString()).getTime() +24 * 60 * 60 * 1000 -1));
    console.log(end_time);
    let end_date = new Date(end_time);
    console.log(end_date);
</script>

在这里插入图片描述

十、取得跳转路径

    beforeRouteEnter(to, from, next) {
        next(vm=>{//这里的vm指的就是vue实例,可以用来当做this使用
            // console.log(typeof(from.path))
            vm.detailsUrl = from.path;//在这vm相当与指向data变量的this。
        })
    },

十一、定时器

 			setTimeout(() => {
                //这个里面是要执行的东西
                
            },0)//这里写多少秒后,执行里面的那个逻辑修改0,这块是毫秒

十二、在vue中使用amfe-flexible

注:flexible他是一个适配方案。
1、下载
npm i -S amfe-flexible
2、在mian.js中引入

import "amfe-flexible/index";

3、如果要修改适配规则在node_modules——>amfe-flexible——>index.js里面改。

(function flexible(window, document) {
    var docEl = document.documentElement;
    var dpr = window.devicePixelRatio || 1;

    // adjust body font size
    function setBodyFontSize() {
        if (document.body) {
            document.body.style.fontSize = 12 * dpr + "px";
        } else {
            document.addEventListener("DOMContentLoaded", setBodyFontSize);
        }
    }
    setBodyFontSize();
    function setRemUnit() {
        /**  
         * 下面这块代表是把屏幕分成二十四等份
         * 这块可以自己修改(也就是屏幕宽度为1920px,分成24等份,每份80px,即就是 1rem就是80 px)
         * 1920px也就是设计稿宽度。
        */
        var rem = docEl.clientWidth / 24;//这块默认是10等份
        docEl.style.fontSize = rem + "px";
    }

    setRemUnit();

    // reset rem unit on page resize
    window.addEventListener("resize", setRemUnit);
    window.addEventListener("pageshow", function (e) {
        if (e.persisted) {
            setRemUnit();
        }
    });

    // detect 0.5px supports
    if (dpr >= 2) {
        var fakeBody = document.createElement("body");
        var testElement = document.createElement("div");
        testElement.style.border = ".5px solid transparent";
        fakeBody.appendChild(testElement);
        docEl.appendChild(fakeBody);
        if (testElement.offsetHeight === 1) {
            docEl.classList.add("hairlines");
        }
        docEl.removeChild(fakeBody);
    }
})(window, document);

4、最后在给一个屏幕的尺寸约束,确保他不会缩小到太小的范围。

@media screen and (max-width: 1024px) {//屏幕小于1024
	html {//把文字大小修改成42px,那就是把现有的屏幕大小除以24得到的42px。
    	font-size: 42px !important;
	}
}
@media screen and (min-width: 1920px) {
	html {//屏幕大于1920px,则是1920px除以24,得到每1rem等于80px,上面的计算等同
		font-size: 80px !important;
	}
}

注:自己计算px与rem比较麻烦,建议在vsc下载cssrem这个插件,这个插件的配置方法如下:
在这里插入图片描述
在这里插入图片描述

十三、WEB移动端在线测试方法

1、使用谷歌和手机联动

1)在手机上下载Chrome Beta,然后在它的里面输入服务地址(即就是谷歌浏览器的打开地址);
下载地址:https://wws.lanzous.com/b01hj061a,也可在手机上扫码直接下载:在这里插入图片描述
2)在PC端谷歌浏览器URL中输入:chrome://inspect/#devices
注:在你看到自己的手机型号,证明,链接成功了,然后在点击
在这里插入图片描述
在这里插入图片描述

2、使用链接进行测试

在vue项目里的public——>index.html中输入:

	<!-- 移动端调试工具 -->
    <script src="//cdn.jsdelivr.net/npm/eruda"></script>
    <script>eruda.init();</script>

注:在手机上会出现一个工具的图标,点开就可以看都控制台了;在上线的时候记得删除或者注释掉。

十四、export default导出和export导出的使用

1、export default


2、export


3、区别

1)export default只能导出一个默认模块,这个模块可以匿名(同时这个模块可以时一个变量,也可以是一个函数),然后在文件里引入就好,这样就可以使用了 import 自己起的模块名 from “模块的文件位置”。
2)export 可以导出多个命名模块,所以在导入的时候,要给模块名加{};import { 模块名 , 模块名 } from ‘模块文件位置’。

十五、判断在用什么设备预览网页

var browser={
	versions:function(){
		var u = navigator.userAgent, app = navigator.appVersion;
		return {
			trident: u.indexOf('Trident') > -1, //IE内核
			presto: u.indexOf('Presto') > -1, //opera内核
			webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
			gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
			mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
			ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
			android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1,//android终端
			iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
			iPad: u.indexOf('iPad') > -1, //是否iPad
			webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
			weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增)
			qq: u.match(/\sQQ/i) == " qq" //是否QQ
		};
	}(),
	language:(navigator.browserLanguage || navigator.language).toLowerCase()
}
console.log(browser);

十六、放大镜插件的使用

1、下载:

npm install viewerjs

2、使用
注:属性配置:https://www.cnblogs.com/10manongit/p/12755602.html
1)方法一
①在mian.js中引用

// 图片放大器(也可以不在全局引入,在那块使用,就在那块引入,这块与使用的那个二选一)
import 'viewerjs/dist/viewer.css';
import Viewer from 'viewerjs';
Vue.use(Viewer);

注:可以放大多张图片,也可以放大一张。
②在组件或者页面里

<template>
    <div>
        <viewer @inited="inited" class="viewer" ref="viewer" toolbar="flase" :options="options">
            <img :src="cristina" alt="">
        </viewer>
        <button type="button" @click="show" >预览</button>
    </div>
</template>
<script>
//这个需要在main.js里引入 或者 在这也使用局部引入
export default {
	data() {
        return {
        	//图片的引入
            cristina:require("@/assets/路径"),
            // 在这块对他进行配置
            options:{
            	//inline
            	inline:true,//开启inline模式,他会没有打开关闭,他会以查看图片的形式直接存在
                inline:false,
                interval:2000,
                navbar:false,
                initialViewIndex:false,
                //配置功能按钮是否显示
                toolbar: {
                    rotateLeft:1,
                    zoomIn:1,
                    reset:1, 
                    zoomOut:1,
                    rotateRight:1
                },
            }
        }
    },
    methods:{
        inited (viewer) {
            this.$viewer = viewer
        },
        show () {
            this.$viewer.show()
        },
    }
}
</script>
<style scoped>

</style>

2)方法二
下面这个案例是基于vantUI的轮播图放大

<template>
    <div>
        <div id="viewers">
            <van-swipe @change="onChange" :autoplay="3000" indicator-color="white">
                <van-swipe-item v-for="(item,index) in imgSvgUrl" :key="index">
                    <img class="svg" :src="item" :alt="index+1" >
                </van-swipe-item>
                <template #indicator>
                    <div class="custom-indicator">
						{{ current + 1 }}/{{length}}
                    </div>
                </template>
            </van-swipe>
        </div>
    </div>
</template>
<script>
//引入
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';
export default {
    data() {
        return {
            current: 0,
            imgSvgUrl:[
                "pictureURL",
                "pictureURL",
                "pictureURL",
                "pictureURL",
                "pictureURL"
            ],
            length:5//这个是图片的张数
        }
    },
    methods: {
        onChange(index) {
            this.current = index;
        },
    },
    created(){
    },
    mounted() {   
        // 在这块取到,并且  去改变属性
        const ViewerDom = document.getElementById('viewers');
        const viewer = new Viewer(ViewerDom, {
            // 相关配置项,详情见下面
            interval:2000,
            // 点击的方法如下
            show:function show(){
                console.log("我打开了放大器")
            },
            hide:function hide(){
                console.log("我关闭了放大器")
            }
        });
    }
}
</script>
<style scoped>
    .svg{
        width:100%;
        height:2rem;
    }
    .van-swipe-item{
        height:2rem;
        width:100%;
        background-color: aquamarine;
    }
    .custom-indicator {
        position: absolute;
        right: 5px;
        bottom: 5px;
        padding: 2px 5px;
        font-size:14px;
        background:transparent;
        color:white;
    }
    .svgtwo{
        height:2rem;
        width:100%;
    }
</style>

十七、对后端返回的long类型的处理

1、下载

npm i json-bigint

2、使用
在axios请求的时候,去使用

//引入封装的数据请求
import {request} from "@/utils/request.js";
//引入json-bigint
import JSONbig from 'json-bigint';
export function getRequest (params){
	return request({
		method: 'get',//发送数据的方式
		url:URL,//地址
		params: params,
		dataType: 'json',//这个是定义数据类型
		transformResponse: [function (data) {//对long类型的数据,进行处理
			try {
				//这块是转换成功
				return JSONbig.parse(data);
			} catch (){
				// 如果转换失败,则包装为统一数据格式并返回
				return {
					data
				}
			}
		}],
		//请求头
		headers: {
			
		}
	})
}

十八、在组件 或者页面中使用路由钩子

    beforeRouteEnter(to, from, next) {
    	//这里的vm指的就是vue实例,可以用来当做this使用,这样就可以获取到页面或者组件里面的data数据。
        next(vm => {

        })
    },
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值