LoginSignup
96

More than 3 years have passed since last update.

Vue.js で json を読み込む

Last updated at Posted at 2018-07-20

静的なデータをコンポーネントと別ファイルで管理したい時にどうぞ。

Vue-cliを使っている場合

例えばassetフォルダ内にjsonファイルを用意して、それをcomponentsフォルダ内のコンポーネントから読み込むときは以下のように書けば良い。

assets/data.json
[
  {
    "id": 1,
    "name": "hogehoge"
  },
  {
    "id": 2,
    "name": "gehogeho"
  },...
]
main.vue
import users from '../assets/data.json'

export default {
  data: () => {
     users: users
  }
}

その他の場合

axiosを使う必要があります

index.html
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="./app.js"></script>
app.js
var app = new Vue({
  data: {
     items:null
  },
  mounted: function () {
    axios.get("./items.json").then(response => (this.items = response))
  }
})

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
96