随笔 - 33  文章 - 0  评论 - 5  阅读 - 15万

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

使用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')
}
});
复制代码

 

 
 
 
posted on   风景1573  阅读(847)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示