LoginSignup
2
3

More than 5 years have passed since last update.

Vue.jsをクラスから使う時のセットアップ

Last updated at Posted at 2015-11-07

まずはHTMLの方ですが、書きたくないのでJadeで失礼します。

index.jade
include ./elements

+html(lang="ja")
  +head
    title Test
  body

    #mario
      p Mario:
        button(@click="jump") Jump
      ul
        li(v-for="item in items" v-text="item.text")

    #luigi
      p Luigi:
        button(@click="jump") Jump
      ol
        li(v-for="item in items" v-text="item.text")

elements がインクルードされていますが、共通部分を外出ししているだけで、特別なことはしていません。
+ が付いている箇所でコールしています。# はdivが作られていて、@ はVueの記法で on を意味します。

ちなみに、elements の内容は↓。

elements.jade
mixin html
  doctype
  html&attributes(attributes)
    block

mixin head
  - var CDN = '//cdnjs.cloudflare.com/ajax/libs/'
  head
    meta(charset="utf-8")
    script(src=CDN + "vue/1.0.1/vue.min.js")
    script(src="main.js" charset="utf-8")
    block

続いて本題のJSですが、Coffeeだとこんな感じ。
ES6で書いても似たようなものですね。

main.coffee
'use strict'

class Mario

  constructor: (@el)->
    @data =
      items: []

    new Vue({el: @el, data: @data, methods: @methods})

  methods:
    jump: (e)->
      obj =
        text: 'Jumped'
      @items.push(obj)
      return

document.addEventListener('DOMContentLoaded', ->
  new Mario('#mario')
  new Mario('#luigi')
  return
, false)

@ はCoffeeだと this と読みます。
あとは methods:@data を必要に応じて追加していくだけで使えます。

結果

Screen Shot 2015-11-07 at 11.53.44 AM.png

現場からは以上です。

2
3
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
2
3