0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

vue.jsを初めて学ぶ① [hello world]

Last updated at Posted at 2020-10-21

vue.jsを学ぶ記事では一貫して、
jsfiddle上で、Vue.jsのCDNを読み込んで使用していく。

jsfiddle → ブラウザで、html,css,vueが実装できる。

Vue.js → CDNが使用できる。

hello world

  • ガイドへ移動
    スクリーンショット 2020-10-21 16.03.10.png
  • scriptタグをindex.htmlに貼り付ける

以下どちらでも可能
スクリーンショット 2020-10-21 16.03.48.png

index.html
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id = "app">
  <p>
    {{message}}
  </p>
</div>
  • scriptタグを使用して、vue.jsのCDNを使用できるようにする
  • {{message}}にて、Vueのmessage内容が反映される。
index.js
new Vue({
 el: '#app',
 data: {
  message: 'Hello World'
 }
})
  • elにて、id'app'を持つ要素にdata(message)をもたせる。

以上で Hello Worldが表示される。

スクリーンショット 2020-10-21 16.12.15.png

Hello Worldを反転させる

  • htmlファイルに、buttonタグとvue専用のDOMイベント v-on:click="メソッド名" を追加。
index.html
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id = "app">
  <p>
    {{message}}
  </p>
  <button v-on:click="reverseMessage">
    メッセージ反転
  </button>
</div>
  • jsファイルに、methodsを追加。htmlで指定したDOMのメソッド名とfunction関数を記述する。この関数がDOMが動作した時の処理になる。

(reverseMessageでは、文字が反転する関数が記述される。)

index.js
new Vue({
	el: '#app',
  data: {
  	message: 'Hello World'
  },
  methods: {
  	reverseMessage: function() {
  		this.message = this.message.split('').reverse().join('')
  	}
  }
})

スクリーンショット 2020-10-21 16.39.51.png

まとめ

  1. htmlファイルにscriptタグを導入し、Vue.jsをインストール
  2. new Vue()で括ることでVue.jsが使用できる
  3. el: htmlファイル内の要素を指定
  4. data: データをもたせる事ができる。さらに、messageで文字列などの要素を持たせる。
  5. jsファイルで指定した要素(idやclass)を、htmlファイルに用意し{{}}で囲み指定する。message要素が表示。
  6. Vue専用DOMのv-on:clickを追加
  7. reverseMessageで、文字反転の関数を呼び出す。
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?