原文https://blog.phyer.cn/article/8369
記錄一下學習webpack+vue碰到的一個大坑,踩這個坑是我才疏學淺的表現,特此引以為戒。因為該坑實在是太坑了!
代碼
header.html
<body> <div id="popup-wrap"> <popup ref="popup"></popup> </div> </body>
header.js
import popup from '../../components/popup/popup.vue' import './header.scss' let header_vue; $(function () { header_vue = new Vue({ el: '#popup-wrap', data: { }, mounted: { // 輸出為{popup: VueComponent} console.log(this.$refs); } components: {popup}, methods: { pop_data: function () { // 輸出為{} console.log(this.$refs); } } }); }); export {header_vue}
other.js
import {header_vue} from "../header/header"; $(function () { header_vue.pop_data() });
`popup.vue`是一個普通的彈窗組件。我在`header.js`中引入該組件,並實例化一個`header_vue`使用了`popup`組件,然后在`other.js`中引入`header_vue`試圖使用`pop_data`函數,該函數僅輸出`header_vue`的`$refs`,經測試,該函數輸出為一個空的對象,但是`mounted鈎子`正常輸出。
我就很納悶,為啥`mounted`輸出正常,函數調用就成空的了呢,Vue也已經掛載完成了啊。
resolve
一番氣急敗壞的debug后,在`header.js`的`$(function())`加上了一句`console.log('ok')`,結果瀏覽器輸出了倆ok。短時間大腦的高速運轉后,我發現了問題的所在:
webpack打包了兩遍`header.js`!
所以解決的辦法就是把`header_vue = new Vue()`改成`window.header_vue = new Vue()`。別處直接用就行了。
尾話
目前沒搞清楚具體的bug出現原因,正常使用webpack多次引入同一個export也沒有出現過此問題。但是肯定是我沒學明白,有大牛知道的話麻煩解答解答。