当你使用Vue.extend()方法,自定义生成一个构造函数时,本地运行可能会发生如下错误
<template>
<div id="home">
<div>home</div>
</div>
</template>
<script>
import Vue from 'vue'
export default {
name: "",
mounted() {
// 创建子组件构造函数 VueComponent
var VueComponentFun = Vue.extend({
template: "<p>{{firstName}} {{lastName}} aka {{alias}}</p>",
data: function () {
return {
firstName: "Walter",
lastName: "White",
alias: "Heisenberg",
};
},
});
// 挂载到一个元素上。
new VueComponentFun().$mount("#home");
},
};
</script>
意思是template编译器不被提供,上面代码中我们使用了template参数,vue框架暂时解析不了
编译器和运行时
vue.js版本构建概念 安装 — Vue.js
vue CLI简单配置 webpack 相关 | Vue CLI
vue的打包文件分为完整版和运行时两种
完整版:(编译器+运行时)
编译器:将模板字符串编译成为 JavaScript 渲染函数的代码,对应vue包中vue.esm.js文件
运行时:创建 Vue 实例、渲染并处理虚拟 DOM 等的代码,对应vue包中vue.runtime.esm.js文件
//比如传入template 选项,此时需要编译器进行编译
new Vue({
el: "#app",
components: { App },
template: "<App />"
})
//不需要编译器
new Vue({
render: h => h(App)
})
官网解释:
打包工具打包时默认引入的是vue.runtime.esm.js(只包含运行时功能), 如果写代码时需要用到编译器,需要修改webpack配置,如下所示:
# vue.config.js
# 添加参数
const { defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
transpileDependencies: true,
publicPath: "./",
configureWebpack: (config) => {
// console.log("config: ", config)
// 默认
// resolve: {
// alias: {
// '@': 'D:\\adaptation_scale\\src',
// 'vue$': 'vue/dist/vue.runtime.esm.js'
// },
// extensions: ['.mjs', '.js', '.jsx', '.vue', '.json', '.wasm'],
// modules: [
// 'node_modules',
// 'D:\\adaptation_scale\\node_modules',
// 'D:\\adaptation_scale\\node_modules\\@vue\\cli-service\\node_modules'
// ]
// }
Object.assign(config.resolve.alias, { vue$: "vue/dist/vue.esm.js" });
},
});