用vue2.0开发做兼容时,你可能会发现vue项目在IE11版本浏览器中是空白的。。。看到空白的页面你可能会懵逼几秒钟,没事,下面我们就来解决这个问题~
让IE11支持vue2.0
首先用npm 安装babel-polyfill
npm install --save-dev babel-polyfill
然后在webpack.base.conf.js
文件中修改module.exports
中的entry
,添加babel-polyfill
:
修改前
module.exports = {context: path.resolve(__dirname, '../'),entry: {app: './src/main.js'},...
修改后
module.exports = {context: path.resolve(__dirname, '../'),entry: {app: ['babel-polyfill', './src/main.js']},...
然后再main.js
中引入:
import 'babel-polyfill'
完成上述一系列操作之后,在IE11浏览器中重新跑下项目,你就会发现,你辛苦做的页面出现了!
但是页面有可能还会没有出现!!!,这时首先查看控制台,看看是否报错,根据报错情况查找原因。在这说再一个特别的原因,static
下的js
文件中用了ES6
的语法,针对这个问题,解决方法如下:
在webpack.base.conf.js
文件中添加resolve('static')
修改前:
module: {rules: {...{test: /\.js$/,loader: 'babel-loader',include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]},...}}
修改后:
module: {rules: {...{test: /\.js$/,loader: 'babel-loader',include: [resolve('src'), resolve('test'), resolve('static'), resolve('node_modules/webpack-dev-server/client')]},...}}
但是如果你的项目中有router-link
标签的话,点击一下你会发现,嗯,又出问题了,路由无法跳转,这是千万不要荒,稳住,下面解决这个问题。
IE11上router-link无法跳转,主要是因为当url的hash change的时候,浏览器没有做出相应。这时候需要做一个兼容,当浏览器是IE11时手动给url加一个hashChange事件
下面是在网上找的两种方法
第一种:
new Vue({el: '#app',router,store,template: '<Layout/>',components: {Layout },render: function (createElement) {if ('-ms-scroll-limit' in document.documentElement.style && '-ms-ime-align' in document.documentElement.style) {window.addEventListener('hashchange', () => {var currentPath = window.location.hash.slice(1)if (this.$route.path !== currentPath) {this.$router.push(currentPath)}}, false)}return createElement(Layout);}})
第二种:直接添加在 main.js 入口文件的最后即可
if ('-ms-scroll-limit' in document.documentElement.style && '-ms-ime-align' in document.documentElement.style) {// detect it's IE11window.addEventListener("hashchange", function(event) {var currentPath = window.location.hash.slice(1);if (store.state.route.path !== currentPath) {router.push(currentPath)}}, false)}