You are using the runtime-only build of Vue where the template compiler is not available ,页面自定义带template内容的组件无法渲染,控制台报错

发布时间 2023-08-07 22:34:45作者: 风景1573
使用vue-cli搭建的项目,页面自定义带template内容的组件无法渲染,控制台报错,页面不展示组件内容,代码如下:
<template>
  <div class="hello">
  my-component:<my-component></my-component>
  </div>
</template>

<script>
import Vue from "vue";
Vue.component("my-component", {
  template: "<div>my-component:这是我写的一个组件!==局部组件</div>",
});

export default {
  name: 'HelloWorld',
}
</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.
问题分析:
您正在使用Vue的仅运行时版本,其中模板编译器不可用。 可以将模板预编译为渲染函数,也可以使用包含编译器的内部版本
问题原因:runtime-compiler和runtime-only,在项目配置的时候,使用npm 包默认导出的是运行时构建,即 runtime-only 版本,不支持编译 template 模板。
 
解决方法有以下几种:
  1. 在vue.config.js文件或者webpack配置文件中添加配置,重新启动项目,刷新页面
module.exports = {
  // webpack配置 - 简单配置方式
  configureWebpack: {
    resolve: {
      alias: {
        // 别名
        vue$: "vue/dist/vue.esm.js", //加上这一句
      }
    }
  },
}
或者:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  configureWebpack: {
    resolve: {
      alias: {
        // 别名
        vue$: "vue/dist/vue.esm.js", //加上这一句
      }
    }
  },
})

 

 
  1. 在vue.config.js文件或者webpack配置文件中添加配置,重新启动项目,刷新页面
module.exports = {
    runtimeCompiler:true   //添加这一行
}
或者:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  runtimeCompiler: true  //添加这一行
})

 

  1. 将预编译的template放入render函数中执行
//template:
  my-component:<my-component></my-component>
  my-component2:<my-component2></my-component2>


//script:以下两种写法都可以
import Vue from "vue";
Vue.component("my-component", {
  //template: "<div>my-component:这是我写的一个组件!==局部组件</div>",
  render: function (h) {
    return h('div', 'Hello, 我是my-component')
  }
});
Vue.component("my-component2", {
  render: function (h) {
  return h('div', {
    attrs: {
      id: 'example'
    },
    style: {
      backgroundColor: 'skyblue',
      color: 'white',
      fontSize: '20px'
    }
  }, 'Hello, 我是my-component2')
}
});