2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Vue.js のサンプル (button クリック、JSON 読み込み)

Last updated at Posted at 2019-04-23

こちらのプログラムを改造して JSON を読み込むようにしました。
Vue.js のサンプル (button クリック、text 表示)

grimm.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<script src="https://unpkg.com/vue@2.6.14"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>グリム童話</title>
</head>
<body>
<h2>グリム童話</h2><p />
<button id='aa' onclick="doAction(this.id)">
赤ずきん
</button>
<button id='bb' onclick="doAction(this.id)">
いばらひめ
</button>
<button id='cc' onclick="doAction(this.id)">
ラプンツェル
</button>
<button id='dd' onclick="doAction(this.id)">
七わのからす
</button>

<div id="app0">
<blockquote>
{{ title }}
</blockquote>
<p />
{{ text }}
</div>

<script src="grimm.js"></script>

<p />
Apr/23/2019 AM 08:25<p />
</body>
</html>
grimm.js
// ---------------------------------------------------------------
//	grimm.js
//
//						Apr/23/2019
//
// ---------------------------------------------------------------
var data_aa = {title: 'こんにちは。',
		text: 'テスト'}
new Vue (
{
	el: '#app0',
	data: data_aa 
})

// ---------------------------------------------------------------
function doAction(id)
{
	const file_json = "data/" + id + ".json"

	axios.get(file_json).then((res) => {
//		console.log("*** doAction *** check ***")
		data_aa.title = res.data.title
		data_aa.text = res.data.text
		})
}

// ---------------------------------------------------------------

JSON ファイル

data/aa.json
{
  "title": "赤ずきん",
  "text": " むかし、あるところに、ちいさな、かわいい女の子がいました。だれでも、ひと目見ただけで、この子がすきになりましたが、なんといっても一ばんかわいがったのは、この子のおばあさんでした。"
}
data/bb.json
{
  "title": "いばらひめ",
  "text": " 昔むかし、王さまとおきさきががおりました。ふたりは毎日、「子どもがほしい!子どもがいればな!」と、言い暮らしていましたが、いつまでたっても、ひとりもさずかりませんでした。"
}
data/cc.json
{
  "title": "ラブンツェル",
  "text": " むかし、あるところに、亭主とおかみさんがおりました。長いあいだ、子どもがほしいと願っていましたが、さずかりませんでした。"
}
data/dd.json
{
  "title": "七のからす",
  "text": " むかし、ある男のひとに、むすこばかり、七人ありました。むすめをほしい、ほしいとねがってきたのですが、ひとりも、さずからなかったのです。"
}

フォルダーの構造

├── data
│   ├── aa.json
│   ├── bb.json
│   ├── cc.json
│   └── dd.json
├── grimm.html
└── grimm.js

次のバージョンで確認しました。

Vue.js v2.6.14
axios v0.27.2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?