【发布时间】:2020-03-30 12:02:05
【问题描述】:
首先,让我说一下我的目标是将 Vue 集成到我现有的代码库中。我还发现 Webpack 非常有用,可以根据我的需要进行设置。并不是说我对 webpack 非常胜任,而是了解了基本的想法并以某种方式做到了。
为了在现有项目中使用 Vue,我选择将其与纯 Javascript 集成,而不是编译 .vue 文件,原因是复杂性、项目要求和时间。因此,在我的代码库中的某个地方,我想初始化一个针对 DOM 元素的 Vue 实例,并在我的 HTML 中对模板进行硬编码。让我在代码中显示它以使其更清晰。以下是我的 HTML 的一部分:
<div id="entry-component">
<p>Hello {{ message }}!</p>
</div>
<!-- I use Django and `verbatim` here to escape Django templating inside. -->
<!-- Also, consider `component` here as a part of HTML page, not in sense of Vue.
A page can have multiple `whatever-component` and initialize multiple `Vue` instances. -->
还有我的 Javascript 文件:
// app.js
// entry point for webpack
// some imports here...
import 'vue'
// I do this because I hardcoded my template (`message` variable) inside
// my HTML and only want runtime Vue.
import './components/entry.js'
// this contains my `Vue` instance
////////////////////////
// ./components/entry.js
import Vue from 'vue'
// otherwise it throws error complaining it cannot resolve what `Vue` is
const entryComponent = new Vue({
el: "#entry-component",
data: {message: "world"}
})
所以,编译成功。但是,我启动了我的开发服务器,转到包含该组件的相关页面,然后发生了一些奇怪的。
首先,它甚至不渲染Hello 部分。这实际上意味着 Vue 已成功加载并安装在目标 DOM 元素上。这是我没有得到的部分。我已经告诉过“用message替换{{message}}。为什么它不渲染它并完全清除#entry-component的内容?
提前致谢。
疑难解答
运行时 Vue 警告 (?)
我认为可能相关的另一件事是浏览器在开发控制台中抛出的警告:
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
这可能是因为我在app.js 中使用了import 'vue'。我只想要运行时 Vue。我不知道这是否会导致 HTML 中硬编码的模板无法呈现。这似乎是一个错误,不知道它是否会停止客户端 Javascript 的执行。
显式导入 Vue 的 Dist 构建
上面的错误给了我一些线索,我想尝试显式地导入 vue 的分发版本。我已经在下面导入但没有运气:
// app.js
// instead of > import 'vue'
import 'vue/dist/vue.js' // still same error
import 'vue/dist/vue.esm.js' // nope
import 'vue/dist/vue.common.js' // no
我还阅读了dist 文件夹中的README.md。它说vue.js 有所有,包括编译器但仍然没有运气。
环境
- 我不知道它是否相关,但我使用 Django,我确信我使用
verbatim来逃避 Django 模板。 - Vue ^2.6.10
- Webpack ^4.41.2
- Webpack CLI ^3.3.10
- NPM 6.12.1
- 节点 12.13.0
【问题讨论】:
-
你必须编译 Vue 模板。
{{ }}语法不是 Vue 运行时可以理解的,它们被 Vue 模板编译器编译成函数调用。 -
@RossAllen |所以我用 NPM 安装它并导入它而不是 vue(或之前/之后?)?
vue-template-compiler是正确的包名吗?