美文网首页
vue 公共方法

vue 公共方法

作者: 不会写代码的机器人 | 来源:发表于2020-06-09 15:46 被阅读0次
main.js
import allFun from './common/commonFun' //公共函数
Vue.use(allFun)

其他组件直接调用commonFun的方法 eg:this.oosCertificate()

commonFun.js
// 公用方法库
//   海王公共函数
export default {
    install(Vue) {
        // oss请求证书
        Vue.prototype.oosCertificate = function () {
            return new Promise((reslove, reject) => {
                let _result = JSON.parse(localStorage.getItem("oss_times"))
                let timestamp = new Date().getTime();
                if (_result == undefined || ((timestamp - _result.times) / 60000 > 15)) {
                    this.$api.get_upload_info()
                        .then((result) => {
                            if (result.code == 0) {
                                localStorage.setItem("oss_times", JSON.stringify(result)); //证书存在缓存
                                reslove(result.times)
                            }
                        })
                        .catch(err => {
                            console.log("获取oss失败", err);
                            this.$toast('图片选择错误');
                            reject(err)
                        });

                } else {
                    console.log(_result);
                    reslove("ok")
                }

            })
        };

        // 上传图片函数
        Vue.prototype.imgUp = function (formData, index) {
            return new Promise((reslove, reject) => {
                let that = this;
                let _result = JSON.parse(localStorage.getItem("oss_times"))
                let OSS = require('ali-oss')
                that.client = new OSS({
                    region: 'oss-cn-shenzhen',
                    accessKeyId: _result.data.accessId,
                    accessKeySecret: _result.data.accessKey,
                    bucket: 'puchi',
                    stsToken: _result.data.securityKey
                });
                put(formData, _result, index);
                // console.log(formData)
                async function put(file, result_data, index) {
                    try {
                        //object-name可以自定义为文件名(例如file.txt)或目录(例如abc/test/file.txt)的形式,实现将文件上传至当前Bucket或Bucket下的指定目录。
                        let UUID = createUUID();
                        let timestamp = Date.parse(new Date())
                        let md5code = that.$md5(UUID + timestamp);
                        // console.log("md5code", md5code)
                        let suffix = await fileinfo(file);
                        // console.log(suffix)
                        let result = await that.client.put(result_data.data.subPath + '/' + result_data.data.fileNamePrefix + md5code + suffix, file);
                        that.res_url.push(result.name); //修改调用页面的imgurl
                        reslove(index)
                    } catch (e) {
                        console.log(e);
                        this.$store.commit('storeIsLoding', false);
                        that.$toast({
                            message: '上传失败',
                            duration: 2000,
                            forbidClick: true,
                        })
                    }
                }
            })

        };

        function createUUID() { //uuid转换摘要
            let d = new Date().getTime();
            if (window.performance && typeof window.performance.now === "function") {
                d += performance.now(); //use high-precision timer if available
            }
            let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                let r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
        }

        function fileinfo(file) { //获取图片文件信息
            return new Promise((reslove, reject) => {
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function (theFile) {
                    let image = new Image();
                    image.src = theFile.target.result;
                    image.onload = function () {
                        let w_h = '_' + this.width + 'x' + this.height
                        let index = file.name.lastIndexOf('.');
                        let suffix = file.name.substring(index);
                        const order = w_h + suffix;
                        reslove(order);
                    };
                };
            })

        }
        Vue.prototype.timestampToTime = function (timestamp) { //时间戳转换时间
            var newtime = (new Date()).getTime()
            var date = new Date(timestamp); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
            let Y = date.getFullYear() + '-';
            let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            let D = date.getDate() + ' ';
            let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':';
            let m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':';
            let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            let chaTime = newtime - timestamp;
            let main = chaTime / 1000 / 60;
            let hour = main / 60;
            let day = hour / 24;
            let time_chan = '';
            if (parseInt(main) < 1) {
                time_chan = '刚刚'
                return time_chan
            } else if (parseInt(main) < 60) {
                time_chan = parseInt(main) + '分钟前'
                return time_chan
            } else if (parseInt(hour) < 24) {
                time_chan = parseInt(hour) + '小时前'
                return time_chan
            } else if (parseInt(day) < 2) {
                time_chan = parseInt(day) + '小时前'
                return time_chan
            } else {
                return Y + M + D + h + m + s;
            }

        }
        Vue.prototype.endorse = function (item) { //点赞文章

            if (this.openid) {
                if (this.is_click_endorse) {
                    this.is_click_endorse = false;
                    if (item.doLIke == 0) {
                        item.doLIke = 1
                        item.likeNumber++;
                    } else {
                        item.doLIke = 0
                        item.likeNumber--;
                    }
                    this.$api.praise_post({
                            targetId: item.postId,
                            type: item.doLIke
                        })
                        .then(res => {
                            if (res.code == 0) {
                                this.is_click_endorse = true;
                            } else {
                                this.is_click_endorse = true;
                                this.$store.commit('storeIsLogin', true);
                                this.$toast({
                                    message: res.msg,
                                    duration: '1000'
                                })
                                if (item.doLIke == 0) {
                                    item.doLIke = 1
                                    item.likeNumber++;
                                } else {
                                    item.doLIke = 0
                                    item.likeNumber--;
                                }
                            }
                            console.log(res)
                        })
                        .catch(err => {
                            this.$toast({
                                message: '哎呀,待会再试试吧',
                                duration: '1000'
                            })
                            if (item.doLIke == 0) {
                                item.doLIke = 1
                                item.likeNumber++;
                            } else {
                                item.doLIke = 0
                                item.likeNumber--;
                            }
                        })
                }
            } else {
                this.$store.commit('storeIsLogin', true);
            }



        }

        Vue.prototype.GetQueryString = function (name) { //获取url上参数
            const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg) || window.location.hash.substring(window.location.hash.search(
                /\?/) + 1).match(reg);
            if (r != null) {
                return unescape(r[2]);
            }
            return null;
        }
        //   判断是否是全面屏
        Vue.prototype.judgeBigScreen = function () { //,这里根据返回值 true 或false ,返回true的话 则为全面屏 
            let result = false;
            const rate = window.screen.height / window.screen.width;
            let limit = window.screen.height == window.screen.availHeight ? 1.8 : 1.65; // 临界判断值  
            // alert('高'+window.screen.availHeight+'宽'+window.screen.availWidth )
            // window.screen.height为屏幕高度
            //  window.screen.availHeight 为浏览器 可用高度
            if (rate > limit) {
                result = true;
            }
            return result;
        };
        Vue.prototype.doCopy = function (val) { //复制到剪切板
            this.$copyText(val).then((e) => {
                this.$toast({
                    message: '分享链接已复制',
                    duration: '1000'
                });
                console.log(e)
            }, (e) => {
                this.$toast({
                    message: '复分享失败',
                    duration: '1000'
                });
                console.log(e)
            })

        };
        Vue.prototype.textIsNull = function (val) { //判断输入框是否为空(包括空格 回车)
            if (val.replace(/\s/g, '').length > 0) {
                return true;
            } else {
                return false;
            }
        };
       Vue.prototype.getIsMobile = function (val) { //判断是pc还是移动端
            var app = navigator.userAgent;
            var isIOS = app.indexOf('iPhone') > -1
            var isAndroid =
                app.indexOf('Android') > -1 || app.indexOf('Linux') > -1
            if (isAndroid) {
                return true
            } else if (isIOS) {
                return true
            } else {
                return false
            }
        };
        Vue.prototype.geteQuipmentClass = function () { //判断是pc还是移动端是否是微信端
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                /* 这是微信浏览器 */
                // if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
                //     // alert("微信移动端")
                //     console.log("微信移动端")
                // } else {
                //     // pc
                //     console.log("微信pc端")
                //     // alert("微信pc端")
                // }
                return true
            } else {
                /* 不是微信浏览器,H5支付 */
                if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
                    console.log("h5移动端")
                    // alert("h5移动端")
                } else {
                    // pc
                    // alert("h5pc端")
                    console.log("h5pc端")
                }
                return false
            }
        };

相关文章

  • vue公共方法

    之前写了公共组件的使用方法,今天有人问我,方法如何抽离?今天写一下,给需要的小伙伴们进行使用。1.写在main.j...

  • vue 公共方法

    其他组件直接调用commonFun的方法 eg:this.oosCertificate()

  • Vue 定义公共方法

    定义的公共方法 调用示例:this.showErrMeg(xxx) main.js引入

  • vue websocket 请求

    首先写一个公共方法 socket.js 使用 test.vue

  • Vue数据流

    数据流是vue2.0新增的插件vuex的一个对象store,用来存储全局的变量及方法,例如:公共的方法和公共组...

  • 公共

    公共注册方法 在@下创建Vue-required文件夹中创建vue-components.js 再 然后嘞在mai...

  • Vue中引用公共方法

    1.在src新建commonFunction文件夹,再新建common.js 2.在main.js中引用commo...

  • Vue 封装echarts公共方法

    在使用Echarts在做数据大屏的时候,需要初始化多个图表,每个图表的都要进行初始化对应的DOM元素绑定var m...

  • vue(utils.js)常用的公共方法的整理

    vue(utils.js)常用方法的封装,以下是我搜集到的认为vue中可能会用到的一些公共方法的整理,在后面开发过...

  • vue加载高德地图,并自定义infoWindow事件

    1. 加载高德地图 公共方法 具体加载方法 2.自定义infoWindow事件 使用Vue.extend()生成html

网友评论

      本文标题:vue 公共方法

      本文链接:https://www.haomeiwen.com/subject/ooastktx.html