一、完整版和运行时

1.定义

  • 完整版:同时包含编译器和运行时的版本。
  • 编译器(下面用**compiler**表示):用来将模板字符串编译成为JavaScript渲染函数的代码。
  • 运行时:用来创建Vue实例、渲染并处理虚拟DOM等的代码。基本上就是除去编译器的其它一切。

    2.深入理解两种区别

    | | Vue完整版本 | Vue非完整版 | 评价 | | :—-: | :—-: | :—-: | :—-: | | 特点 | 有 compiler | 无 compiler | 无 compiler 少30%体积 | | 视图 | 写在 HTML 里或者写在 template 选项 | 写在 render 函数里
    用 h 来创建便签 | h是尤雨溪写好传给 render 的 | | cdn 引入 | vue.js | vue.runtime.js | 文件名不同。生产环境改为后缀为.min.js | | webpack 引入 | 需要配置 alias | 默认使用此版本 | 尤雨溪配置 | | @vue/cli 引入 | 需要额外配置 | 默认使用此版本 | 尤雨溪、蒋豪群配置 |

最佳实践:总是使用非完整版,然后配合vue-loadervue文件

思路:

  1. 保证用户体验,用户下载的 JS 文件体积更小,但只支持 h 函数
  2. 保证开发体验,开发者可直接在 vue 文件里写 HTML 标签,而不写 h 函数
  3. 中间的转换过程让 loader 来做,vue-loader把 vue 文件里的 HTML 转为 h 函数

    二、template 和 render 怎么用

    1.完整版直接使用template(可以直接写HTML)

  • 基本写法

    1. new Vue({
    2. template: '<div>{{ n }}</div>'
    3. })
  • 添加+1按钮

    1. new Vue({
    2. el:'#app',
    3. template:`<div>
    4. {{n}}
    5. <button @click="add">+1</button>
    6. </div>`,
    7. data:{
    8. n:0
    9. },
    10. methods:{
    11. add(){
    12. this.n += 1
    13. }
    14. }
    15. })

    2.非完整版(render(){}

  • 基本写法

    1. new Vue({
    2. render (h) {
    3. return h('div', this.n)
    4. }
    5. })
  • 添加+1按钮

    1. new Vue({
    2. el: '#app',
    3. render(h) {
    4. return h('div', [this.n, h('button', {on: {click: this.add}}, '+1')])
    5. },
    6. data: {
    7. n: 0
    8. },
    9. methods: {
    10. add() {
    11. this.n += 1
    12. }
    13. }
    14. })

    三、Vue 单文件组件

  • 新建一个Demo.vue文件,里面有三个标签

    • template 写视图
    • script 写其他
    • style 写css样式 ```vue

  1. - `main.js`内容;直接导出这个`Demo`,然后`render`一下(`render`会自动将`template`里内容转化为`vue`可识别的)
  2. ```vue
  3. // 单文件组件
  4. import Demo from './Demo.vue'
  5. new Vue({
  6. el: '#app',
  7. render(h) {
  8. return h(Demo)
  9. }
  10. })
  • 打印出的Demo,自带render方法,不需要自己写

image.png

  • 打印出的Demo.render.toString()

image.png

四、如何用 codesandbox.io 写 Vue 代码

注:登录之后只能创建50个项目

具体步骤:

  • 点击create sandbox

image.png

  • 点击Vue

image.png

  • 创建之后,基本的文件就都自动生成了

image.png

  • 如果想要保存到本地,点击File>Export to ZIP;导出压缩文件

image.png