Vue – Component

Component

Vue component is same as React Component and Angular directive.
One page has a lot of UI component inside, and some are independent and some are dependent.

Consider several page, there are a lot of common parts.
Sometimes, one component should be re-usable(easy to use any parts).

Basic Template

Vue.component

<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  </head>
  <body>
    <div id="app">
      <p>{{ message }}</p>
      <list-title></list-title>
    </div>
    <script>
    Vue.component('list-title', {
      template: '<h1>Title</h1>'
    })
    new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue.js!'
      }
    })
    </script>
  </body>
</html>

This is simple component example. Use template and use it inside Vue range.

Vue.component, Vue.extend

It’s good explain from stackoverflow. component calls extend inside.

Parent – Child : Simple case

<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  </head>
  <body>
    <div id="app">
      <p>{{ message }}</p>
      <fruits-list-parent></fruits-list-parent>
    </div>
    <script>
    var fruitsListChild = Vue.extend({
      template: '<h1>{{name}}</h1>',
      data : function() {
        return {
          name: 'test'
        }
      }
    })

    var fruitsListParent = Vue.extend({
      template: '<div>Parent<fruits-list-child></fruits-list-child></div>',
      components: {
        'fruits-list-child': fruitsListChild
      }
    })

    new Vue({
      el: '#app',
      components: {
        'fruits-list-parent': fruitsListParent
      },
      data: {
        message: 'Hello Vue.js!',
        name: 'List'
      }
    })
    </script>
  </body>
</html>

Vue object use custom component named ‘fruits-list-parent’,
fruits-list-parent uses custom component named ‘fruits-list-child’.
Parent should register child custom as components data inside.
Also, child component has data: function() { return }
It means that data is valid only this component.

Separate File

This is next step. I will explain another post.

Ref

Vue.js入門 ―最速で作るシンプルなWebアプリケーション