VUE 兼容IE9+ 之路

566 阅读3分钟

1. 不兼容ES6

安装

 npm install babel-polyfill es6-promise--save

在main.js中的最前面引入

import 'babel-polyfill'
require('es6-promise').polyfill();

找到build文件夹下的webpack.base.conf.js文件修改:

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry:{
    app: ["babel-polyfill", "./src/main.js"],
  },

.babelrc文件修改:

"presets": [
    ["env", {
      "modules": false,
      "useBuiltIns": "entry",
    }],
    "stage-2"
  ],

2. Swiper轮播

swiper需要下载2.7.6版本

引入方式:

import Swiper from "swiper/dist/idangerous.swiper.min.js";
import "swiper/dist/idangerous.swiper.css";

注:2.x和其他版本不同:

mode:'vertical',//swiper2 设置滑动方向

注:Echarts和Swiper一起使用时,设置loop为true,导致echarts图形出不来; 因为使用swiper loop:true后,slide被克隆导致id不再是唯一,所以echarts的图形出不来

解决办法:改用calssname,记住获取classname需要循环

let mychartArr = document.getElementsByClassName('myChart1');
for(var i=0;i<mychartArr.length;i++){    
    var myChart = echarts.init(mychartArr[i]);    
    myChart.setOption(option);
}

3. IE报错 "SyntaxError: strict模式下不允许一个属性有多个定义

标签中有重复定义属性去掉就可以

4. IE下 backspace 返回上一级

banBackSpace.js

export  function banBackSpace(e){
         var ev = e || window.event;//获取event对象
          var obj = ev.target || ev.srcElement;//获取事件源
          var t = obj.type || obj.getAttribute('type');//获取事件源类型
          //获取作为判断条件的事件类型
         var vReadOnly = obj.getAttribute('readonly');
          //处理null值情况
          vReadOnly = (vReadOnly == "") ? false : vReadOnly;
        //当敲Backspace键时,事件源类型为密码或单行、多行文本的,
        //并且readonly属性为true或enabled属性为false的,则退格键失效
         var flag1=(ev.keyCode == 8 && (t=="password" || t=="text" || t=="textarea") && vReadOnly=="readonly")?true:false;
         //当敲Backspace键时,事件源类型非密码或单行、多行文本的,则退格键失效
        var flag2=(ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea") ?true:false;
        //判断
         if(flag2){
            return false;
         }
         if(flag1){
            return false;
        }
 }

App.vue

import {banBackSpace} from './api/preventBackspace'
export default {
  mounted() {
    document.onkeypress=banBackSpace
    document.onkeydown=banBackSpace
  },
}

5. IE报错 TypeError: 对象不支持“remove”属性或方法"

原始报错代码:

copy(data) {
        if (!data) return;
        let url = data;
        let oInput = document.createElement('input');
        oInput.value = url;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象;
        document.execCommand("Copy"); // 执行浏览器复制命令
        this.$message.success('复制成功');
        oInput.remove();
      },

解决后代码:

copy(data) {
        if (!data) return;
        let url = data;
        let oInput = document.createElement('input');
        oInput.value = url;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象;
        document.execCommand("Copy"); // 执行浏览器复制命令
        this.$message.success('复制成功');
        if(!!window.ActiveXobject || "ActiveXObject" in window) { // 判断是否是IE
            oInput.removeNode(true);
        } else {
           oInput.remove();
        }
      },

6. Placeholder不显示

自定义指令:

var placeIE = {
  install: function(Vue) {
    Vue.directive("placehie", {
      inserted: function(el) {
        if (("placeholder" in document.createElement("input"))) {
          return;
        }
        if (/^el/.test(el.className)) {
          el = el.querySelector("[placeholder]");
        }
        var placeholder = el.getAttribute("placeholder") || "请输入";
        var span = document.createElement("span");
        span.className = "ie-placeholder";
        span.innerText = placeholder;
        span.style.left = "15px";
        span.style.lineHeight = "32px";
        el.parentNode.style.position = "relative";
         el.insertAdjacentElement("afterend", span);
         el.onfocus = function(event) {
          span.style.display = "none";
        };
        el.onblur = function(event) {
          if (!event.target.value) {
            span.style.display = "inline";
          }
        };
        el.oninput = function(event) {
          if (event.target.value) {
            span.style.display = "none";
          } else {
            span.style.display = "inline";
          }
        }
      },
      unbind: function(el) {
        el.onfocus = el.onblur = el.oninput = null;
      }
    })
   }
};
export default placeIE

在入口文件main.js中全局注册指令

import placeIE from "./api/PlaceholderIE"; 
Vue.use(placeIE);

使用方式:

<el-input  v-placehie  placeholder="请输入"  v-model="searchvalue"> </el-input>

7. Axios 不兼容

最简单的方法下载axios0.18.0及以下版本

IE9中跨域无法携带请求头信息,开发时可用代理

8. IE new Date("2021-03-06 16:36:22").getTime()返回NAN

方法1:正则

new Date("2021-03-06 16:36:22".replace(/-/g,'/')).getTime();

方法2:Date.parse()

parse() 方法可解析一个日期时间字符串,并返回 1970/1/1 零点距离该日期时间的毫秒数。

var time = '"2021-03-06 16:36:22"';
Var newTime = Date.parse(time.replace(/-/g,'/'));

9. IE 9 backspace、del键时,input的change事件失效(el-input在ie9下删除文本无效的解决方法)

 (function (d) {
        d.addEventListener('selectionchange', function() {
          var el = d.activeElement;
          if (el.tagName === 'TEXTAREA' || (el.tagName === 'INPUT' && el.type === 'text')) {
            var ev = d.createEvent('CustomEvent');
            ev.initCustomEvent('input', true, true, {});
            el.dispatchEvent(ev);
          }
        });
      })(document)
  };

10. IE下报错 requestAnimationFrame”未定义

main.js中添加:

(function () {
  var lastTime = 0;
  var vendors = ['ms', 'moz', 'webkit', 'o'];
  for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
      window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
      window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||
          window[vendors[x] + 'CancelRequestAnimationFrame'];
  }

  if (!window.requestAnimationFrame) {
      window.requestAnimationFrame = function (callback, element) {
          var currTime = new Date().getTime();
          var timeToCall = Math.max(0, 16 - (currTime - lastTime));
          var id = window.setTimeout(function () { callback(currTime + timeToCall); },
              timeToCall);
          lastTime = currTime + timeToCall;
          return id;
      };
  }

  if (!window.cancelAnimationFrame) {
      window.cancelAnimationFrame = function (id) {
          clearTimeout(id);
      };
  }
}());

11. 背景渐变色

background: linear-gradient(90deg,#2B55FB,#5F5AFB); 
-ms-filter: "progid:DXImageTransform.Microsoft.gradient (GradientType=1, startColorstr=#2B55FB, endColorstr=#5F5AFB)";//老的dx引擎,都是local渲染

如果使用filter会影响当前元素中定位元素的高度,就改用图片吧,如下:

@media (min-width:0\0) and (min-resolution:.001dpcm) {
	/*ie9 仅ie9识别*/
  .app .el-header-primary{
    background: url('../bg.png') no-repeat;
    background-size: 100% 100%;
  }
}

12. display:flex 布局

改用position、float、display:inline-block