LoginSignup
1
2

More than 3 years have passed since last update.

Vue CLIで作成したindex.htmlからオブジェクトを取得する

Last updated at Posted at 2020-03-16

タイトルの内容をもうちょっと詳しく

  • Vue CLIで作ったプロジェクト
    • ディレクトリ構成はデフォルトのまま
  • 画面表示用にオブジェクトを渡したいが、諸事情によりindex.htmlに書くことしかできない
    • index.htmlにscriptタグを書いて埋め込む
  • なのでVue側からindex.htmlに記載された値を取得する

サンプルコード

index.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <title>args sample</title>
    </head>
    <body>
        <div id="app"></div>
        <script>
        var htmlArgs = [
        {
            "key1":"hoge",
            "key2":"fuga"
        },
        {
            "key1":"foo",
            "key2":"bar"
        }
        ];
        </script>
    </body>
</html>
App.vue
<template>
  <div id="app">
    <ul>
      <li v-for="arg in args" v-bind:key="arg.key1">
        key1={{arg.key1}} / key2={{arg.key2}}
      </li>
    </ul>
  </div>
</template>
<script>
/* global htmlArgs */
export default {
  name: 'App',
  data: function(){
    return {
      args: htmlArgs
    }
  },
}
</script>
<style>
</style>

解説

今回のキモになるのは、App.vueの/* global htmlArgs */です。
これが無い状態で実行すると、以下のようなエラーとなります。

cmd
ERROR  Failed to compile with 1 errors
error  in ./src/App.vue

Module Error (from ./node_modules/eslint-loader/index.js):

C:\Users\anonymous\sample\src\App.vue
  12:34  error  'htmlArgs' is not defined no-undef

✖ 1 problem (1 error, 0 warnings)

App.vueの中にhtmlArgsがいないのでエラーになります。
無いものを使おうとしているわけですから、当然ですね。

先ほどの/* global htmlArgs */htmlArgsはglobalにいる(からファイル内に無くてもスルーしてくれ)と宣言して、エラーを防ぐという効果があります。

これでindex.htmlにあるオブジェクトを取得できるようになりました。
めでたしめでたし。

参考

アンビエント宣言が’no-undef’ルールにひっかかる件
https://teratail.com/questions/226017

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