「Vue」浅入分析 Vue 两个版本

862 阅读2分钟

具体查看官网链接

代码仓库地址:
github.com/huyiling111…

一、Vue 的两个版本

Vue 有两个版本,分别是完整版和非完整版,

1.1 完整版

完整版同时包括编译器(compiler) 和 运行时(runtime)
编译器的功能是将模板字符串编译为 JavaScript 渲染函数(render 函数)的代码
运行时的功能包括创建 Vue 实例、渲染并处理虚拟 DOM 等,它包括除了编译器的其他所有功能

1.2 只包含运行时版

只包含运行时版就只有运行时,没有编译器

二、两个版本的区别

Vue 完整版Vue 只包含运行时版
特点有 compiler没有 compiler
视图写在 HTML 里,或者写在 template 选项里写在 render 函数里,用 h 创建标签
cdn 引入vue.jsvue.runtime.js
webpack 引入需要配置 alias默认使用
vue@cli 引入需要额外配置默认使用

那究竟应该使用哪一个版本呢?
最佳实践是使用 非完整版,然后用 vue-loader 引入 compiler
整个流程思路如下:

  1. 对于用户来说,非完整版 (即 runtime 版)体积小,用户体验好,但只支持 h 函数
  2. 对于程序员来说,只能写 h 函数的话,开发体验不好,如果有 compiler, 开发者就能写更直观更语义化的 HTML 标签和 template, 所以我们需要一个 compiler
  3. webpack 通过 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('{on:{click:this.add}’,'+1'])
   }

//不完整版使用vue-loader

//先创建一个demo.vue文件,在里面构建视图
    import Demo from "./Demo.vue"
    console.log( Demo.render.toString)
    //这里的demo是一个对象,
     new Vue({
       el: "#app",
       render(h) {
         return h(demo)
       }
       //h就是creatElement,用来生成html DOM元素的
     })

注意:通过打印 Demo.render.toString 可以发现 vue-loader 把 template 里的内容翻译成 如下内容:

_c("div", { staticClass: "red" }, [
    _vm._v(" " + _vm._s(_vm.n) + " "),
    _c("button", { on: { click: _vm.add } }, [_vm._v("+1")])
  ])
}