Search code examples
vue.jsvuejs2

error component is not defined when using child tag in vue instance


I've just started to learn vuejs and I've tried to run a little code applying what I've learned by creating a basic component inside the vue instance using Vue.component('nameOfComponent', { });, yet nothing is displayed and I got Uncaught ReferenceError: HelloWorld is not defined

What's the fault in the following code ?

<html>
<head>
<head>
<body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>


<div id="app">
  <HelloWorld @updated="fct" :numb="firstNumb"/>
</div>

<script type="text/javascript">
Vue.component('HelloWorld', { 
  template:'<h1 @click="mymeth">{{" click to increase !}}{{ numb }}</h1>',
  props: {
    numb: Number
  },
  methods:{
    mymeth(){
     this.$emit('updated', this.numb+1);
    console.log("value firstNumb in child component ", this.numb)
    },
  }
});
new Vue({
 'el':'#app',
 data:{
      firstNumb:5,
},
components: { HelloWorld },

 methods:{
     fct(e){
    this.firstNumb=e;
    console.log("value firstNumb in parent component ", this.firstNumb)
    },
 
 }
 });
 
 </script>
 </body>
 </html>

Solution

  • It should be noted off the bat that Vue 2 has reached EOL (end of life) and you should be learning Vue 3 if anything. Regardless, to your question...

    The component needs to be assigned to a variable to be properly referenced within new Vue()

    const HelloWorld = Vue.component(...)
    
    new Vue({
      ...
      components: { HelloWorld },
      ...
    })
    

    Also when adding custom elements directly in the DOM you must use kebab-case as noted in the Vue 2 documentation:

    only kebab-case names are valid directly in the DOM

    <div id="app">
      <hello-world @updated="fct" :numb="firstNumb"/>
    </div>
    

    Correcting a few other minor mistakes/typos, the working code then is provided below:

    <html>
    <head>
    <head>
    <body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    
    
    <div id="app">
      <hello-world @updated="fct" :numb="firstNumb"/>
    </div>
    <script>
    
    const HelloWorld = Vue.component('HelloWorld',{
      template:'<h1 @click="mymeth">click to increase ! {{ numb }}</h1>',
      props: {
        numb: Number
      },
      methods:{
        mymeth(){
          this.$emit('updated', this.numb+1);
          console.log("value firstNumb in child component ", this.numb)
        },
      }
    });
    
    new Vue({
      el : '#app',
      data() {
        return {
          firstNumb: 5
        }
      },
      components: { HelloWorld },
      methods:{
        fct(e){
          this.firstNumb=e;
          console.log("value firstNumb in parent component ", this.firstNumb)
        },
      }
    });
    </script>
    </body>
    </html>