用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瀏覽器中重新跑下項目,你就會發現,你辛苦做的頁面出現了!
但是如果你的項目中有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 IE11
window.addEventListener("hashchange", function(event) {
var currentPath = window.location.hash.slice(1);
if (store.state.route.path !== currentPath) {
router.push(currentPath)
}
}, false)
}