vue使用template模式报错:You are using the runtime-only build of Vue where the template compiler is not ava

vue使用template,报错的问题

局部注册这个组件:

// 父组件
<div>
  <input type="text" v-model="input" placeholder="please input" />
  <test-child :test="test" />
</div>
  
// 子组件, 通过局部注册方式
components: {
  testChild: {
    template: `<div v-bind="$attrs">hello</div>`,
  }
},

但是testChild组件没有渲染,并报错:

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.

看到这篇:https://www.jianshu.com/p/c35c2c178fe5 以及You are using the runtime-only build

vue有两种形式的代码
分别是compiler(模板)模式和runtime模式(运行时)
vue模块的package.json的main字段默认为runtime模式,指向了"dist/vue.runtime.common.js"位置

我们的文件中使用的是(模板)compiler模式的,因此出现上面的报错信息。

解决方法

解法一: 代码修改为render:

testChild: {
    updated() {
      console.log(this.$attrs.test)
    },
    render(h) {
   	  return (<div {...{attrs:this.$attrs}}>hello</div>)  // jsx
    },
} 

v-bindv-onjsx 上的使用:

v-bind ='$attrs'     => {...{attrs:this.\$attrs}}
v-on='$listeners'    => {...{on:this.\$listeners}}

解法二: vue.config.js文件加上webpack的配置:

  configureWebpack: (config) => {
    config.resolve.alias = {
      ...config.resolve.alias,
    
      // 加上这句
      'vue$': 'vue/dist/vue.esm.js' 
    }
  }

重新跑一下就好了

解法三: 修改引入的Vue:import Vue from 'vue/dist/vue.esm.js'

// 默认runtime模式,指向了"dist/vue.runtime.common.js"位置
import Vue from 'vue';

// 如果要采用template模式, 要修改成template模式的路径:vue/dist/vue.esm.js
import Vue from 'vue/dist/vue.esm.js'

这种方式举例:

import Vue from 'vue/dist/vue.esm.js'

// 标准的vue组件引入
import childComponent from '@/views/childComponent.vue'

// 动态组件,这里采用的是模板编译, 与现有使用的runtime模式不一致,要么修改成render函数,要么修改vue的引入, 这里用后者
 const Card = Vue.extend(childComponent)

 // 动态挂载相应的组件
 const vueComponent = new Card({
   el: '#toImg',
   propsData: {
     [paramsName]: { // props 参数信息}
   }
 })

template与render的区别

来源:https://www.jianshu.com/p/0555e7acc5d1

  1. VUE一般使用template来创建HTML,而使用javascript来创建html要使用render函数。

  2. template逻辑简单,易理解,但灵活性不足,template最终还是要通过render的方式再次进行编译;
    render渲染很灵活,通过createElement的方式创建虚拟DOM。

  3. render(高)的性能要比tempate(低)要高。

  4. render函数的优先级大于template,同时存在最终渲染render

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值