vue.jsvuejs2vuejs3vue-component

local registration went wrong


I generated a new project using vue 2, then I wanted to apply local registration, but I"m getting compile errors

screenshot of error

the following shows the changes files:

main.js

import Vue from 'vue'
import maNewComp from './maNewComp.vue'

Vue.config.productionTip = false
new Vue({
  render: h => h(maNewComp),
//local registration
 components:{
  'my-new-test': MyNewTest,
 }
}).$mount('#app')

component that is calling the registred component (maNewComp)

<template>
    <div>
        <h3>welcome</h3>
    </div>
    <my-new-test></my-new-test>
  </template>
  
  <script>
  
  export default {
 
  }
  </script>

the related component (MyNewTest)

<template>
    <div>
        <h3>{{ greeting }}</h3>
    </div>
  </template>
  
  <script>
  
  export default {
 
    data(){
        return{
        greeting: 'hello !'
        }
    }
  }
  </script>
  
 


Solution

  • Vue 2 has a limitation on a single root element per component. This means that <template> needs to contain only one direct child, e.g. div wrapper:

    <template>
      <div>
        <div>
            <h3>welcome</h3>
        </div>
        <my-new-test></my-new-test>
      <div>
    </template>
    

    Another problem is that MyNewTest isn't correctly registered. It should be either be directly imported and specified in components option of the component that uses it, which is maNewComp. Or be registered globally in main entry point:

    import MyNewTest from './MyNewTest.vue'
    ...
    Vue.config.productionTip = false
    Vue.component('MyNewTest', MyNewTest)
    new Vue({
      render: h => h(maNewComp),
    })
    .$mount('#app')