LoginSignup
31
33

More than 5 years have passed since last update.

Vue.jsの$elに指定するDOMのルール、Componentの使いドコロ

Last updated at Posted at 2015-04-17

概要

Vueコンストラクタに指定するelオプション にいろいろ指定していて気づいたことのメモ。

環境

Rails+Webpack+Gulp+Vue+Coffeescript

メモ

基本

elオプション には、id、もしくはひとつしかないclassを指定しないといけない。

# good
id = new Vue(
  el: '#id'
  data: {
    text: 'はろう'
  }
)

# good
button_send = new Vue(
  el: '.button--send' # ひとつしか存在しないクラス
  data: {
    text: 'はろう'
  }
)

# bad(というか動かない)
button = new Vue(
  el: '.button' # 複数存在するクラス
  data: {
    text: 'はろう'
  }
)

Componentを使いまわす

では、複数要素に使いまわすにはどうするか。
→同じviewmodel内でのcomponentの使い回しは可能。

id = new Vue(
  el: '#id'
  data: {
    text: 'はろう'
  }
  components: {
    'my-component': {
      template: '<span>{{text}}</span>'
    }
  }
)

DOMはこちら。

<div id="id">
  <div v-component="my-component" v-with="text: text"></div>
  <div v-component="my-component" v-with="text: text"></div>
  <div v-component="my-component" v-with="text: text"></div>
</div>

Componentを別ファイルにする

componentを別ファイルに分けて、Webpackでrequireすればcomponentは1ファイルで使いまわせる。

id = new Vue(
  el: '#id'
  data: {
    text: 'はろう'
  }
  components: {
    'my-component': require('my-component')
  }
)

some_id = new Vue(
  el: '#some_id'
  data: {
    text: 'こんにちは'
  }
  components: {
    'my-component': require('my-component')
  }
)
my-component.coffee
# このファイルを使い回せばOK
module.exports = {
  template: '<span>{{text}}</span>'
}

参考

31
33
2

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
31
33