martincarstens
10/5/2016 - 8:34 PM

VueJS 2 Parent + Child Components

VueJS 2 Parent + Child Components

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Parent-Child Vue</title>
        <script type="text/javascript" src="https://unpkg.com/vue@2.0.1/dist/vue.js"></script>
    </head>
    <body>
        
        <div id="example">
          <parent-component></parent-component>
        </div>
        
    </body>
    
    <script type="text/x-template" id="parent-template">
      <div>A custom component! <child-component my-message="child o mine">{{ myMessage }}</child-component> </div>
    </script>
    
    <script type="text/x-template" id="child-template">
      <div>This is a {{ myMessage }} component</div>
    </script>
    
    <script type="text/javascript">
    
        var ChildComponent = Vue.extend({
            props: ['myMessage'],
            template: '#child-template',
        })
    
        var ParentComponent = Vue.extend({
          data: function() {
              return {
                  myMessage: ''
            }  
          },
          template: '#parent-template',
          components: {
            // <my-component> will only be available in Parent's template
            'child-component': ChildComponent
          }  
        })
        // register
        Vue.component('parent-component', ParentComponent)
        // create a root instance
        new Vue({
          el: '#example'
        })
        
    </script>
    
</html>