vue.extend的问题

问题场景

使用Vue.extend时

<template>
  <div>
   <div id="mount-point"></div>
  </div>
</template>
<script>
import Vue from 'vue'
export default {
    mounted() {
      const Profile = Vue.extend({
          data() {
              return {
                  firstName: 'Yan',
                  lastName: 'Hello',
                  alias: '最后'
              }
          },
          template: '<p>{{firstName}} {{lastName}} 组合 {{alias}}</p>'
      })
      new Profile().$mount('#mount-point')
    },
}
</script>

运行后报
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.
在这里插入图片描述
原因是:
项目中使用的构建版本是runtimeonly,要让上面代码有效应该在vue.config.js中配置

module.exports = {
	runtimeCompiler: true,
}

runtimeonly与runtimeCompiler

runtimeCompiler:完整版(运行时+编译器)

编译器:用来将模板字符串编译成为 JavaScript 渲染函数的代码。
运行时:用来创建 Vue 实例、渲染并处理虚拟 DOM 等的代码。基本上就是除去编译器的其它一切。

如果你需要在客户端编译模板 (比如传入一个字符串给 template 选项,或挂载到一个元素上并以其 DOM 内部的 HTML 作为模板),就将需要加上编译器,即完整版:

// 需要编译器
import Vue from 'vue'
import App from '@/App'
new Vue({
	el: "#app",
	components: { App },
	template: "<App />"
})

是不在打包时进行编译的,是在客户端(浏览器)运行时进行编译的,所以要使用待编译器的完整版本

runtimeonly: 只包含运行时

当使用 vue-loader 或 vueify 的时候,*.vue 文件内部的模板会在构建时预编译成 JavaScript。你在最终打好的包里实际上是不需要编译器的,在浏览器中可直接运行,所以只用运行时版本即可。

// 不需要编译器
import Vue from 'vue'
import App from '@/App'
new Vue({
	el: "#app",
	render: h => h(App)
})

因为运行时版本相比完整版体积要小大约 30%,所以应该尽可能使用这个版本。如果你仍然希望使用完整版,则需要在打包工具里配置一个别名:

module.exports = {
  // ...
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js' // 用 webpack 1 时需用 'vue/dist/vue.common.js'
    }
  }
}

对比

在这里插入图片描述
下图为两种模式下,npm run dev后,在谷歌控制台查看main.js引入的vue文件版本
runtimeonly
在这里插入图片描述
runtimeCompiler
在这里插入图片描述

因为在 Vue.js 2.0 中,最终渲染都是通过 render 函数,如果写 template 属性,则需要编译成 render 函数,那么这个编译过程会发生在运行时,所以需要带有编译器的版本。很显然,这个编译过程对性能会有一定损耗,所以通常我们更推荐使用 Runtime-Only 的 Vue.js。

组件上做一些新逻辑功能

extend.js

import Vue from 'vue'
import Toast from '@/components/Toast'
const Toast=Vue.extend(Toast)
//......Profile相关代码
export {
    Profile,
    Toast
}

使用

<template>
  <div>
   <div id="mount-point"></div>
  </div>
</template>
<script>
import {Profile} from '../extend'
export default {
    mounted() {
      new Profile().$mount('#mount-point')
    },
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值