使用vue-cli3创建一个空白项目,有时候莫名其妙的创建全局变量无效,如:
从管网文档直接拿一个组件demo
// main.js
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
// Demo.vue
<template>
<div class="demo">
<button-counter/>
</div>
</template>
报错:
[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.
原因:
vue有两种形式的代码 compiler(模板)模式和runtime模式(运行时),vue模块的package.json的main字段默认为runtime模式, 指向了”dist/vue.runtime.common.js”位置。
解决方法1
在项目根目录创建vue.config.js文件,添加vue别名,代码:
// vue.config.js
module.exports = {
configureWebpack: {
resolve: {
alias: {
//添加vue别名
'vue$': 'vue/dist/vue.esm.js'
}
}
}
//或
// vue.config.js
module.exports = {
chainWebpack: (config) => {
config.resolve.alias
//添加vue别名
.set('vue$', 'vue/dist/vue.esm.js')
}
}
添加vue别名,import Vue from ‘vue’ 这行代码被解析为 import Vue from ‘vue/dist/vue.esm.js’,直接指定了文件的位置,没有使用main字段默认的文件位置
解决方法2:
所有引用vue的都以vue/dist/vue.esm.js引入
import Vue from 'vue/dist/vue.esm.js'
学习了