LoginSignup
8
6

More than 5 years have passed since last update.

VueJS 文字列テンプレート

Posted at

公式のComponentページで度々出てくる 文字列テンプレートがイマイチ把握できなかったので、まとめてみた。

公式より

# キャメルケース vs ケバブケース

HTML の属性は大文字と小文字を区別しません。そのため、非文字列テンプレートを使用する場合、キャメルケースのプロパティ名を属性として使用するときは、それらをケバブケース (kebab-case: ハイフンで句切られた) にする必要があります:

Vue.component('child', {
  // JavaScript ではキャメルケース
  props: ['myMessage'],
  template: '<span>{{ myMessage }}</span>'
})

<!-- HTML ではケバブケース -->
<child my-message="hello!"></child>

繰り返しになりますが、もし文字列テンプレートを使用する場合は、この制限は適用されません。

とあります。
属性値のKEYがキャメルケースでも、表示されるものが文字列テンプレートなのですね。

そこで、以下のファイルを用意しました。

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>vue</title>
  </head>
  <body>
    <div id="app">
      <child my-message="hello! parent"></child>
      <App/>
    </div>
    <!-- built files will be auto injected -->
  </body>
</html>
main.js
import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false;

Vue.component('child', {
    props: ['myMessage'],
    template: '<span>{{ myMessage }}</span>'
});

new Vue ({
             el        : '#app',
             components: {
                 App
             }
         });
App.js
<template>
  <div id="app">
    <child my-message="hello! child"></child>
  </div>
</template>

<script>


export default {
  name: 'app',
}
</script>

これで、画面を表示すると

hello! parent
hello! child

と表示されます。
どちらもケバブケースなので、正常に表示されます。

次に、index.htmlの属性値のKEYをキャメルケースに修正します。

index.html
...

    <div id="app">
      <child myMessage="hello! parent"></child>
      <App/>
    </div>

...

画面表示すると

hello! child

制限に引っかかり、「hello! parent」が表示されません。故に、index.htmlは文字列テンプレートではないです。

次に、App.htmlの属性値のKEYをキャメルケースに修正します。

App.html
<template>
  <div id="app">
    <child myMessage="hello! child"></child>
  </div>
</template>

...

画面表示は

hello! child

「hello! child」は表示されました。
故に、App.htmlは文字列テンプレートになります。

なるほど。

8
6
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
8
6