Vue CLIで作成したindex.htmlからオブジェクトを取得する
5506 ワード
タイトルの内容をもうちょっと詳しく
- Vue CLIで作ったプロジェクト
- ディレクトリ構成はデフォルトのまま
- 画面表示用にオブジェクトを渡したいが、諸事情によりindex.htmlに書くことしかできない
- index.htmlに
script
タグを書いて埋め込む
- index.htmlに
- なので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
Author And Source
この問題について(Vue CLIで作成したindex.htmlからオブジェクトを取得する), 我々は、より多くの情報をここで見つけました https://qiita.com/Naoki_kkc/items/82b6ab5e29fd5dd340da著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .