题意:VueJS 与 Webpack:将 JavaScript 从 Vue 文件中分离

问题背景:

I'm learning VueJs and have followed a tutorial to produce a working app using the vue-cli WebPack template. All works fine; but I'm a bit OCD and hating that VS2017 doesn't format inline javascript in the vue file so:

我正在学习VueJs,并且按照一个教程使用vue-cli的Webpack模板创建了一个可以正常工作的应用。一切都很正常;但是我有点强迫症(OCD),很不喜欢Visual Studio 2017(VS2017)不能格式化Vue文件中的内联JavaScript代码,所以:

  • I move the javascript out from users.vue to a separate file users.js so...   我将JavaScript代码从users.vue文件中移出,放入了一个单独的文件users.js中,所以……
  • now VS2017 happily formats the js code, highlights bracket pairs etc and   现在,Visual Studio 2017(VS2017)能够愉快地格式化JavaScript代码、高亮显示括号对等等,并且
  • include as <script src> in the original vue.   并在原始的Vue文件中将其作为<script src>包含进来。

Now when I npm run dev I get:

现在,当我运行npm run dev时,我得到:

[Vue warn]: Failed to mount component: template or render function not defined. (found in <Users>) vue.esm.js (559,1)

...and obviously the component doesn't load.

……而且显然,组件没有加载。

Have to be honest I'm at a bit of a loss where to start looking. Am I trying something I shouldn't in splitting out the js, or is there maybe something wrong with the default WebPack set up? I can't believe there's anything wrong splitting out the js as surely when I get beyond tutorials in to real world then reuse and separating from the component has to be possible?

老实说,我有点不知道该从哪里开始查找问题。我是在尝试一些不应该做的拆分JavaScript的事情吗,还是默认的Webpack设置可能有问题?我不认为拆分JavaScript会有什么问题,因为当我超越教程进入实际开发时,重用和从组件中分离出来肯定是可行的吧?

On a side note is there a plugin to format inline javascript in Vue files on VS2017? I've got the VueJs 2017 and CodeMaid extensions but neither has helped formatting code.

另外,VS2017有没有可以格式化Vue文件中内联JavaScript的插件?我已经安装了VueJs 2017和CodeMaid扩展,但它们都没有帮助格式化代码。

I've created an example of the problem at   我已经创建了一个示例来说明这个问题,位于GitHub - 9swampy/SplitVueJs: Sample demonstrating difficulties splitting JS from Vue single file component

问题解决:

vuejs/core · Discussions · GitHub supplied an answer. To be fair there wasn't enough detail in my question without looking at the GitHub repo; bascially I had introduced a naming conflict by not explictly pointing the vue import to users.vue and it was defaulting to users.js instead.

GitHub上的vuejs/core讨论区给出了答案。说实话,如果不查看GitHub仓库的话,我的问题中细节确实不够充分。基本上,我之所以遇到问题,是因为我没有明确地将vue的import指向users.vue,而是让它默认指向了users.js,从而引发了命名冲突。

Hence updating App.vue from

因此,更新App.vue从

import Hello from './components/Hello'

to        更新为下面的内容

import Hello from './components/Hello.vue'

...fixed the issue.

解决这个问题

Doh :)

更多推荐