LoginSignup
7
7

More than 5 years have passed since last update.

爆速でvue.js使ってViewModelを試すよ ヽ(゚ー゚*ヽ)(ノ*゚ー゚)ノわぁい

Last updated at Posted at 2015-02-26

結論

  • ブラウザのみで試した。jsfiddle, jsbin いいね。
  • CORS対応のAPIは便利です。
  • qiita.comのAPIとvue.js使ってjavascriptタグが付いた最新記事一覧を表示するサンプルつくった

はじめに

この記事では以下の絵文字を大事な個所で使用中

  • :exclamation: 注意点
  • :boom: 予期せぬ例外やエラーメッセージ
  • :sunny: 解決方法・お役立ち情報

:computer: 簡単なサンプルをqiita.comのAPI、vue.jsを試す目的で作ってみた。

簡単なjsを試すなら jsfiddle , jsbin とかがオススメ。

ソースコードとか

  • :sunny: vue.js は cdnjs のCDNから読み込むよ ※cdnjsはマイナーなjsライブラリをホストしてる
  • :sunny: #qiita_items のdiv要素を用意してvue.jsのオブジェクトからバインドできるようにする
<!DOCTYPE html>
<html>
<head>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.11.5/vue.js"></script>
<script src="http://code.jquery.com/jquery-git2.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="content">
    <div id="qiita_items">
      <button v-on="click: reload">RELOAD</button>
      <div v-repeat="items">
        <h4>{{title}}</h4>
      </div>
    </div>

  </div>
</body>
</html>
  • :sunny: js中のコメントにいろいろ記載しました
var qiita_items = new Vue({
  el: "#qiita_items", // ここでdivにバインド
  data: {items:[]},
  methods: {
    reload: function(event){
      $.ajax({
        cache: true, // キャッシュ効かせたいけど、うまいくいかない
        url: "https://qiita.com/api/v2/tags/javascript/items",
        dataType: "json",
        headers: { // ヘッダーで直接指定しても効果は無い
          'Cache-Control': 'max-age=3600' 
        },    
        success: function(data) {
          // ViewModel のデータを書き換えてDOMに反映させる
          qiita_items.items = data;
        }
      }); 
    }
  }
});

$(function(){
  qiita_items.reload();

});
7
7
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
7
7