在main.js文件中创建IIFE方法时出现奇怪的错误。以下是重现它的步骤,goto命令提示符
vue init webpack-simple test
cd test
npm install test
npm run dev
编辑main.js文件并在最后添加此方法
(function test() {
console.log('test');
})();
它将在控制台上抛出以下错误
Uncaught TypeError: (intermediate value) is not a function
at eval (eval at <anonymous> (build.js:978), <anonymous>:13:3)
at Object.<anonymous> (build.js:978)
at __webpack_require__ (build.js:660)
at fn (build.js:84)
at Object.<anonymous> (build.js:1378)
at __webpack_require__ (build.js:660)
at build.js:709
at build.js:712
如果我将测试作为普通函数并将其称为test(),那么它不会抛出错误,为什么在创建IIFE时会出现问题?
答案 0 :(得分:1)
问题是Vue模板不使用分号。所以你有这个代码:
new Vue({
el: '#app',
render: h => h(App)
})
(function test() {
console.log('test');
})();
但是空白是微不足道的,你真正拥有的是:
new Vue({
el: '#app',
render: h => h(App)
})(function test() {
console.log('test');
})();
相当于:
const vue = new Vue({
el: '#app',
render: h => h(App)
})
vue(function test() {
console.log('test');
})();
这会出现以下错误:
Uncaught TypeError: vue is not a function
这正是你所拥有的,但这一次vue
有一个名字,而不是一个中间值。
这是省略分号时需要注意的一个案例。