原文https://blog.phyer.cn/article...
记录一下学习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也没有出现过此问题。但是肯定是我没学明白,有大牛知道的话麻烦解答解答。