0
点赞
收藏
分享

微信扫一扫

vue常用挂载的方法;vue 全局动态修改title、keywords、description

心如止水_c736 2022-04-15 阅读 36
vue.js

const install=(Vue,router)=>{

    // 跨页面传值
    //this.$HWBUS.$on('fn',res=>{
    //     console.log(res)
    // })//监听
    // this.$HWBUS.$emit('fn',999)//传值
    Vue.prototype.$HWBUS=new Vue()


    // 打印操作
    // html:需要打印页面的html代码,样式必须行内
    // type:需不需要打印
    Vue.prototype.$printFn=(html,type=1)=>{
        var userAgent = navigator.userAgent.toLowerCase(); //取得浏览器的userAgent字符串
            if (userAgent.indexOf("trident") > -1) {
              this.$message.error('请使用google或者360浏览器打印')
              return false;
            } else if (userAgent.indexOf('msie') > -1) {
              this.$message.error('请使用google或者360浏览器打印')
              return false;
            } else {//其它浏览器使用lodop
              var headstr = "<html><head><title></title></head><body>";
              var footstr = "</body></html>";
              var printData = html; //获得 div 里的所有 html 数据
              var wind = window.open("", "newwin","toolbar=no,scrollbars=yes,menubar=no");
              wind.document.body.innerHTML = headstr + printData + footstr;
              if(type==1){
                wind.print();
              }
        }
    }
    // 去除字符串空格
    // isBoolean=true:当数据为空字符串的时,返回false
    Vue.prototype.$trim=(str,isBoolean)=>{
        if (str == null) {
          str = "";
        }
        let thisStr=str.replace(/(^\s*)|(\s*$)/g, "")
        if(isBoolean){
            if(thisStr==''){
                return false
            }else{
                return thisStr;
            }
        }
        return thisStr;
    }
    // 文件预览
    // ops = {
        // "pdf": true, //word文档尝试以pdf方式显示,默认false
        // "watermark": "XDOC文档预览", //水印文本,显示水印
        // "saveable": false, //是否允许保存PDF,默认true
        // "printable": false, //是否允许打印PDF,默认true
        // "copyable": false, //是否允许选择复制内容,默认true
        // "toolbar": false, //是否显示底部工具条,默认true
        // "title": "文档预览", //自定义标题
        // "expire": 30, //预览链接有效期,单位分钟,默认永久有效
        // "limit": "1,3", //限制页数,如:“5”表示只显示前5页,“2,5”表示从第2页开始的5页,对pdf/doc/docx/ppt/pptx有效
        // "mtime": 1633093801, //文件修改时间戳(精确到秒)或修改时间(如:2021-10-01 21:10:01),值改变刷新缓存,实时预览
    // };
    Vue.prototype.$previewFile=(value,ops={})=>{
        let url=`http://view.xdocin.com/xdoc?_xdoc=${value}`
        for (var a in ops) {
            url += "&" + a + "=" + encodeURIComponent(ops[a]);
            
         }
        window.open(url)
    },
    // 文件下载
    Vue.prototype.$downloadFile=(content,fileName='')=>{
        if(content instanceof Array){
            content.forEach(item=>{
                let aLink = document.createElement('a')
                aLink.download = fileName;
                aLink.setAttribute('href',item)
                // a.href = url
                aLink.click()
            })
        }else{
            let aLink = document.createElement('a')
            aLink.download = fileName;
            aLink.setAttribute('href',content)
            // a.href = url
            aLink.click()
        }
       
    },
    // 计算时间差
    Vue.prototype.$dayCha=(value,geshi='天-小时-分-秒',type='string')=>{
        let geshiArray=geshi.split('-')
        var chaTime=value;
        var day=parseInt(chaTime/86400)
        var yu=chaTime % 86400
        var hour=parseInt(yu/3600)
        var yuH=yu % 3600
        var min=parseInt(yuH/60)
        var yuM=yuH%60
        var sec=yuM
        if(type=='string'){
            let str=''
            if(day>0)str+=day+geshiArray[0]
            if(hour>0)str+=hour+geshiArray[1]
            if(min>0)str+=min+geshiArray[2]
            if(sec>0)str+=sec+geshiArray[3]
            if(str==''){
                str='-'
            }
            return str
        }else{
            return {day:day,hour:hour,minute:min,second:sec}
        }
        
    }


    // 复制
    Vue.prototype.$copyToClipboard=(value, cb)=>{
        const textarea = document.createElement("textarea");
        textarea.value = value;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand("copy");
        document.body.removeChild(textarea);
        cb && cb();
    }
   

    // 获取页面url参数
    Vue.prototype.$getQueryVariable=(variable)=>{
        var vars=[]
		if( window.location.hash!=''){
			var query0 = window.location.hash.split('?')[1];
			if(query0)vars = query0.split("&");
			
		}else{
			var query = window.location.search.substring(1);
			if(query)vars = query.split("&");
		}
		let queryObject={}
		for (var i = 0; i < vars.length; i++) {
		    var pair = vars[i].split("=");
			queryObject[pair[0]]=pair[1]
		}
		if(variable){
			if(queryObject[variable] && queryObject[variable]!=''){
				return queryObject[variable]
			}else{
				return false;
			}
		}else{
			return queryObject
		}
    }

    // 生成唯一UUid
    Vue.prototype.$uuid=()=>{
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now(); //use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;    // d是随机种子
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    }
}
export default  install

import install from './assets/appConfig/install'
install(Vue) 

 

路由:
 

{
   path: "xxx",
   name: "xxx",
   component: () =>import('..xxx'),
   meta: {
      title: 'xxx',
      keywords:'xxx',
      description:'xxx'
   },
},

 实现

router.beforeEach((to,from,next)=>{
  /*********动态修改keywords和description*************/
  if(Object.keys(to.meta).length>0 && to.matched.length>0){
    let this_meta=to.matched[to.matched.length-1].meta
    console.log(this_meta,'---this_meta---')
    if(this_meta.title)document.title=this_meta.title
    let head = document.getElementsByTagName('head');
    let meta_keyword=document.createElement('meta');
    if(document.querySelector('meta[name="keywords"]')){
      document.querySelector('meta[name="keywords"]').setAttribute('content',this_meta.keywords)
    }else{
      meta_keyword.setAttribute('name','keywords')
      meta_keyword.setAttribute('content',this_meta.keywords)
      head[0].appendChild(meta_keyword)
    }
    let meta_description=document.createElement('meta');
    if(document.querySelector('meta[name="description"]')){
      document.querySelector('meta[name="description"]').setAttribute('content',this_meta.description)
    }else{
      meta_description.setAttribute('name','description')
      meta_description.setAttribute('content',this_meta.description)
      head[0].appendChild(meta_description)
    }
  }
  /**********************************************/
  next()
})
举报

相关推荐

0 条评论