LoginSignup
0
0

More than 1 year has passed since last update.

#vue.js の component が分かりにくいので手で動かして理解する ( 公式チュートリアルより ) ( Codepen )

Last updated at Posted at 2019-04-03

Tutorial

Introduction — Vue.js

TD; DR

手を動かせ。

なにやら図解されている

image

よく分からないので

とりあえず手を動かしたい。

Code

ハッシュやら使われていてなかなかわかりにくい。

<div id="app-7">
  <ol>
    <todo-item
      v-for="item in groceryList"
      v-bind:todo="item"
      v-bind:key="item.id"
    ></todo-item>
  </ol>
</div>
Vue.component('todo-item', {
  props: ['todo'],
  template: '<li>{{ todo.text }}</li>'
})

var app7 = new Vue({
  el: '#app-7',
  data: {
    groceryList: [
      { id: 0, text: 'Vegetables' },
      { id: 1, text: 'Cheese' },
      { id: 2, text: 'Whatever else humans are supposed to eat' }
    ]
  }
})

ただの配列にしてみる

自分にわかりやすいように 変数名的なものも変えてゆく。

<html>
    <head>
        <link rel="stylesheet" href="index.css">
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
    
    <div id="app-7">
      <ol>
        <todo-item
          v-for="grocery in groceryList"
          v-bind:item="grocery"
        ></todo-item>
      </ol>
    </div>
        <script src="index.js"></script>
    </body>
</html>
Vue.component('todo-item', {
  props: ['item'],
  template: '<li>{{ item }}</li>'
})

var app7 = new Vue({
  el: '#app-7',
  data: {
    groceryList: [
      'Vegetables',
      'Cheese',
      'Whatever else humans are supposed to eat'
    ]
  }
})

同じく動作する

Vue.js Playground

image

js側の理解

Vue.component('todo-item', {

こいつでHTML的に独自要素を定義できる

  props: ['item'],

こいつが HTML側で v-bind:item= 的な記述を可能にする
js 側に記述したテンプレでも同じ変数名で値が受け取れるようになる

  template: '<li>{{ item }}</li>'

その名の通りHTMLのテンプレ
props で定義した名前が変数として使える
公式チュートリアルではハッシュだったが、ここでは文字列を入れているだけ

HTML側の理解

独自定義した component を記述できる

<todo-item></todo-item>

配列データのループ

v-for="grocery in groceryList"

js の props で定義した名前で v-bind とか出来る様子

v-bind:item="grocery"

その他

js側の props が配列なので、別名も追加できるんじゃない?など色々と試したり

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0