SoFunction
Updated on 2025-04-12

Vue Component Learning Tutorial

When learning vue, it is difficult to learn components, especially communication between components, so to summarize the component part of the official document.

Register components

Global Components

The syntax is as follows: the component template needs to be wrapped with a root tag. data must be a method

('component-name',{
  template:'<div><h1>Title</h1><span>Author Information</span></div>',
  data(){
    return{
      message:'Properties of Component'
    }
  },
  methods:{

  }
})

Local components

var com = {
  template:'<div><h1>Title</h1><span>Author Information</span></div>',
  data(){
    return{
      message:'Properties of Component'
    }
  },
  methods:{

  }
}

new Vue({
  components:{
    'compontent-name':com
  }
})

Component communication

prop passes parent component data to child component

 <div id='app'>
   <child :msg=message></child>
 </div>

&lt;script&gt;
  ('child', {
    props: ['msg'],
    template: '&lt;p&gt;{{msg}}&lt;/p&gt;'
  })

  new Vue({
    el: '#app',
    data: {
      message: 'Parent component data'
    }
  })
&lt;/script&gt;

Using the props option of the child component, the parent component can pass data to the child component, but the child component cannot request the data of the parent component to be modified.

Non-parent-child component communication

Need to use an empty Vue instance to manage

<div id='app'>
  <com-a></com-a>
  <com-b></com-b>
</div>
var bus = new Vue();

var coma = {
  template: '&lt;p @click="send"&gt;{{adata}}&lt;/p&gt;',
  data(){
    return {
      adata: 'a's data'
    }
  },
  methods:{
    send(){
      // Trigger this event      bus.$emit('data-to-b', );
    }
  }
  
};

var comb= {
  template: '&lt;p&gt;{{bdata}}&lt;/p&gt;',
  data(){
    return {
      bdata: 'b's data'
    }
  },
  mounted(){
    // Listen to events, get the data of component a, and perform related operations    bus.$on('data-to-b', function (msg) {
       = msg;
    }.bind(this));
  }
};

new Vue({
  el:'#app',
  components: {
    'com-a': coma,
    'com-b': comb
  }
})

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.