一、Vue 的两个版本
Vue 有两个版本,完整版和运行时版
完整版:同时包含编译器和运行时的版本,编译器就是用来将模板字符串编译成为 JavaScript 渲染函数的代码
运行时:用来创建 Vue 实例、渲染并处理虚拟 DOM 等的代码。基本上就是除去编译器的其它一切
二、两个版本的区别
Vue 完整版 | 运行时版 | 评价 | |
---|---|---|---|
特点 | 有 compiler(编译器) | 没有 compiler | compiler 占40%体积 |
视图 | 写在 HTML 里,或者写在 template 选项 | 写在 render 函数里,用 h 创建标签 | h 是写好传给 render 的 |
cdn 引入 | vue.js | vue.runtime.js | 文件名不同,生产环境后缀为 .min.js |
webpack 引入 | 需要配置 alias | 默认使用此版 | 尤雨溪配置的 |
@vue/cli 引入 | 需要额外配置 | 默认使用此版 | 尤雨溪、蒋豪群配置的 |
最佳选择:使用运行时版,然后配合 vue-loader 和 vue 文件
思路:
- 对于用户来说,运行时版可以保证用户体验,下载的 JS 文件体积更小,但只支持 h 函数
- 对于开发者来说,只能写 h 函数的话,开发体验不好,如果有 compiler, 开发者就能写更直观更语义化的 HTML 标签和 template, 所以我们需要一个 compiler
- Vue-loader 就可以引入 compiler, 把 Vue 文件里的 HTML 标签和 template 在构建时预编译成 h 函数,同时满足用户和开发者的需求
三、template 和 render 的用法
// 需要编译器
new Vue({
template: '<div>{{ hi }}</div>'
})
// 不需要编译器
new Vue({
render (h) {
return h('div', this.hi)
}
})
template 标签和 JS 里的 template
//vue文件中的template标签
<template>
<div id="app">
{{n}}
<button @click="add">+1</button>
</div>
</template>
//js中的template
template : `
<div id="app">
{{n}}
<button @click="add">+1</button>
</div>
`
render 函数
// 运行时版在 js 中构建视图
render(h){
return h('div',[this.n,h('button',{on:{click:this.add}},'+1')])
}
// 运行时版使用 vue-loader
// 先创建一个demo.vue文件,在里面构建视图
import demo from "./Demo.vue"
new Vue({
el: "#app",
render(h) {
return h(demo)
}
})
四、使用 codesandbox.io 在线写 Vue 代码
在线写 Vue 代码,无需任何本地的安装依赖
*本文为鲲游北冥的原创文章,著作权归本人和饥人谷所有,转载务必注明来源