前端

[Vue]之不同构建版本的解释

2020-03-19  本文已影响0人  是苏菇凉呀
前言:假设你用 vue-cli 创建了一个 vue 项目,如下

index.html 中

<div id="app">
  <h1>{{text}}</h1>
</div>

main.js 中

import Vue from 'vue'
new Vue({
  el: "#app",
  data: {
    text: "hello"
  }
})

npm run serve 启动项目打开页面后,你会发现报错了

[Vue warn]: 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>)

这是因为你使用的是 vue 的 runtime-only 版本,它不支持这样写,使用 vue-cli 创建的项目,默认配置的就是 vue.runtime.js 版本

一、Vue 不同的构建版本
1. 完整版

同时包含编译器(用来将模板字符串编译成 js 渲染函数的代码)和运行时的版本

2. 只包含运行时版(非完整版)

用来创建 Vue 实例,渲染并处理虚拟 DOM 等的代码,基本上就是除去编译器的其他一切

二、所以,解决最开始的问题有3种办法
1. 引入完整版
<div id="app">
  <h1>{{text}}</h1>
</div>

<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>

<script>
  new Vue({
    el: '#app',
    data: {
      text: "hello"
    }
  });
</script>

弊端:完整版相较于非完整版体积较大

2. 使用 render 函数来生成 VNode
new Vue({
  el: '#app',
  render(h){
    return h('div', this.text)
  },
  data: {
    text: "hello"
  }
});
render 函数的参数是 createElement 函数,它会返回一个 VNode ,它的简写是 h,将 h 作为 createElement 的别名是 Vue 生态系统中的一个通用惯例

弊端:必须使用 render 函数并传入 h 参数构造出所有的元素

3. 单文件组件

使用 webpack 的 vue-loader(vue-cli 已经帮我们配置好了这个加载器)
App.vue文件如下:

<template>
  <div id="#app">
      <h1>{{text}}</h1>
  </div>
</template>

<script>
  export default {
    name: 'App',
    data(){
      return {
        text: "hello"
      }
    }
  }
</script>
因为 Vue 是虚拟 DOM ,所以单文件 App.vue 经过 vue-loader 处理,由 vue-template-compiler 将 template 模板编译生成 render 函数

优点:是非完整版,体积小,并且不需要写 render 函数

总结

以上我们对 vue 不同的构建版本有了一个了解,也对使用 Vue 实例有了一些概念,
最完美的方法就是使用单文件组件,使用 vue-cli 创建的项目就是只包含运行时版(非完整版),所以,直接使用单文件组件是最方便快捷的

上一篇 下一篇

猜你喜欢

热点阅读