vue單文件組件沒法獲取$refs的問題

原文https://blog.phyer.cn/article/8369

 

記錄一下學習webpack+vue碰到的一個大坑,踩這個坑是我才疏學淺的表現,特此引覺得戒。由於該坑實在是太坑了!css

代碼html

header.html

vue

<body>
<div id="popup-wrap">
<popup ref="popup"></popup>
</div>
</body>

 

header.jswebpack

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.jsweb

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()`。別處直接用就好了。this

尾話

目前沒搞清楚具體的bug出現緣由,正常使用webpack屢次引入同一個export也沒有出現過此問題。可是確定是我沒學明白,有大牛知道的話麻煩解答解答。

相關文章
相關標籤/搜索