LoginSignup
0
0

More than 3 years have passed since last update.

Vue.js ディレクティブの基礎2

Last updated at Posted at 2020-05-03

Vue.js ディレクティブの基礎2

前回の記事はこちら
Vue.js ディレクティブの基礎1

双方向データバインディング v-model

jsfiddleで実際に記述しながら読むことをおすすめします。

双方向データバインディングでは
Vue.jsとhtmlが双方向に同期します。

dataオブジェクトの値変更→テンプレートの値変更
テンプレートの値変更→dataオブジェクトの値変更

サンプルコードを書いてみます。

index/html
<div id="app">
  <p>
    <input type="text" v-model="message">
  </p>
   <p>
    <input type="text" v-model="message">
  </p>

  <pre>{{ $data }}</pre> <!-デバッグ用-->

</div>



<script src ="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
index.js
var app = new Vue({
  el:'#app',
  data:{
    message:'Hello Vue.js!'
  }
})

実行結果
Image from Gyazo

上のinputタグで中身を書き換えると
Vue.jsのdataオブジェクトの中身が書き換わり
下のinputタグと同期するという流れです。

Vue.jsのdataオブジェクトを書き換えると
両方のinputタグの中身が同期して書き換わります。

コンポーネントとは

コンポーネントはページを構成するUI部品です。
よく使う機能をコンポーネント化することで
コードの可読性が良くなります。

helloと表示するコンポーネントを作成して
3回繰り返して表示してみましょう。

index/html
<div id="app">
  <hello-component></hello-component>
  <hello-component></hello-component>
  <hello-component></hello-component>
</div>

<script src ="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
index.js
Vue.component('hello-component',{
    template:'<p>hello</p>'
})

var app = new Vue({
    el:'#app'
})

実行結果
Image from Gyazo

コンポーネントはvueインスタンス作成よりも上に記述します。

ここまでで基本のディレクティブは終了です。
次回はこれまでの内容を利用してtodoアプリを作成します。

Vue.jsで作るtodoアプリ

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