在删除了很多已有的代码和文件之后
此时src目录里有main.js,而public目录里则有index.html。
index.html大概长这样:
<body>
<div id="app"></div>
</body>
我们使用模板语法将内容vue实例插入#app
。
index.html
<body>
<div id="app">{{message}}</div>
</body>
main.js
import Vue from 'vue.vue'//可以不写后缀
new Vue{
el:'#app',
data:{
message:"Hello World"
}
}
我们来预览时,页面不会出现任何结果,并且会收到控制台warning:
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.
(found in
<Root>
)
warning的意思是,因为我们使用的Vue是runtime-only版本,没有template compiler,所以我们看不到预览结果。
warning建议我们两种解决方案:
- 在render中采用预编译的template:pre-compile the templates into render functions
- 在build时使用compiler:use the compiler-included build
根据warning可以推理出以下信息:
- Vue需要编译器才能将template模板字符串编译成为 JavaScript 渲染函数
- Vue runtime-only版本没有template编译器,所以无法在html文件中插入template模板
- vue-cli 生成的 vue 项目默认引入Vue runtime-only版本
vue的两个版本
在vue官网中提供了两种vue版本:vue.js和vue.runtime.js。
-
vue.js包含编译器,所以可以直接将将template模板编译成AST,再转化为render函数。
-
vue.runtime.js不包含编译器,所以必须提供render函数。
根据官网,如果直接操作需要在客户端编译模板 (比如传入一个字符串给 template 选项,或挂载到一个元素上并以其 DOM 内部的 HTML 作为模板),就将需要完整版:
客户端视图VM
<div id="hi">{{message}}</div>
// 需要编译器 vue.js支持
new Vue({
el:'#hi',
data(){
return{
message:"hi"
}
}
})
或者
<template></template>
// 需要编译器 vue.js支持
new Vue({
template: '<div> hi </div>'
})
如果不需要再客户端直接操作模板,那么模板的操作需要通过render函数实现: 客户端视图VM
<div id="hi"></div>
// 不需要编译器,vue.runtime.js支持
new Vue({
el:'#hi',
data:{
message:"hi"
},
render (h) {
return h('div', this.message)
}
})
单文件组件 single-file components
vue官网建议使用vue.runtime.js,因为vue.runtime.js除去编译器之后要比vue.js体量减轻30%,并且当使用 vue-loader 或 vueify 的时候,*.vue 文件内部的模板会在build时预编译成 JavaScript。
所以当我们通过打包工具进行预览操作的时候,我们也只需要使用vue.runtime.js。
这也意味着,使用单文件组件既可以实现“在客户端直接操作模板”,又能够采用vue.runtime.js,并且还能获得如下优势:
· 完整语法高亮· CommonJS 模块
· 组件作用域的 CSS
就和没有使用框架时差不多呢
<!-- my-component.vue -->
<template>
<div>This will be pre-compiled</div>
</template>
<script src="./my-component.js"></script>
<style src="./my-component.css"></style>