Vue被分为两个版本,即完整版(vue.js)和非完整版(vue.runtime.js)
1.完整版
- 完整版含有编译器(compiler)和runtime
- 编译器可以将模板字符串编译为JS渲染函数(render)的代码
- runtime功能有Vue实例,渲染并处理虚拟DOM等
2.非完整版
只含有runtime的版本,就是非完整版
两个版本的具体区别
| Vue完整版 | 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文件,
思路:
- 保证用户体验,非完整版 (即runtime版)体积小,但只支持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
new Vue({
...
template : `
<div id="app">
{{n}}
<button @click="add">+1</button>
</div>
`
...
})
render函数
假设需要实现一个简单的+1功能
非完整版中,在.js文件下
//main.js
new Vue({
el: '#app',
data: {
n: 0,
},
render(h) {
return h('div', [
this.n,h('button',
{
on: {
click: this.add,
},
},
'+1',
),
]);
},
methods: {
add() {
this.n += 1;
},
},
});
而使用了vue-loader之后,
先创建一个Demo.vue
//Demo.vue
<template>
<div>
{{n}}
<button @click="add">+1</button>
</div>
</template>
<script>
export default {
data(){
return {
n:0
}
},
methods:{
add(){
this.n += 1
}
}
}
</script>
随后在.js文件中,将其引用
//main.js
import Demo from './Demo.vue'
new Vue({
el:'#app',
render(h){
return h(Demo)
},
})
在线使用Vue的神器
平时可以用CodeSandbox来写vue代码,这样可以省去一些安装步骤,方便又直接