LoginSignup
1
2

More than 5 years have passed since last update.

Vue.js:webpackを使わずにコンポーネントを実装する

Posted at

テスト用のVue.jsアプリを作るときに、動作確認しやすいようにvue-cliを使わずにCDNからスクリプトを読み込む形式で作りました。このときにどのようにコンポーネントを実装すればよいか調べるのに時間がかかったため、簡単に整理してみました。

ポイント

  • スクリプト読み込み
    • Vue.js本体 → コンポーネント → メイン(Vueインスタンス生成)の順で読み込む。
    • head要素に上記の順序でscript要素を組み込むめばよい。(deferを指定するとレンダリングをブロックせずに高速化できる。)
  • テンプレート
    • 以下のいずれかの方法でVueコンポーネントのtemplateプロパティに設定する。(参考
    • HTMLのhead要素に <script type="text/x-template> でテンプレートを記述し、templateプロパティにセレクタ(#で始まる文字列)を指定して参照する。(src属性を使って外部ファイルに切り分けることはできない。)
    • templateプロパティに文字列としてHTMLを記述する。

サンプルアプリ

index.html

<html>
    <head>
        <!-- Vue.jsアプリケーション読み込み
             ※ new Vue() 実行前にコンポーネントを読み込むこと。 -->
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js" defer></script>
        <script src="./component/string-template.js" defer></script>
        <script src="./component/script-template.js" defer></script>
        <script src="./script.js" defer></script>

        <!-- scriptテンプレートを使ったコンポーネント -->
        <script type="text/x-template" id="script-template">
            <div>
        <p>Script Template</p>
      </div>
        </script>
    </head>
    <body>
        <!-- Vueアプリのマウントポイント -->
        <div id="app"></div>
    </body>
</html>

script.js

const app = new Vue({
  el: '#app',
  template: `
    <div>
      <string-template />
      <script-template />
    </div>
  `
})

component/string-template.js

Vue.component('string-template', {
  template: `
    <div><p>String Template</p></div>
  `
})

component/script-template.js

Vue.component('script-template', {
  template: '#script-template'
})
1
2
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
1
2