LoginSignup
1
1

More than 1 year has passed since last update.

Vue.jsで外部JSONファイルを定期的に読み込んで、動的に子供コンポーネントに表示させる

Posted at

はじめに

定期的にJSONを読み込み、そのまま表示させたい。
そんなことをしるならなにやら、Vue.jsがいいのかなぁ。どうなのかなぁ。
Vue.jsでの方法を検証してみた。

開発環境

ide:IntelliJ IDEA
os:Windows10

開発

ターミナルで開発環境を作ります。

vue create .

public内にjsonを用意。

data.json
{
  "data": [
    {
      "name": "name1",
      "message": "file data 1"
    },
    {
      "name": "name2",
      "message": "file data 2"
    },
    {
      "name": "name3",
      "message": "file data 3"
    }
  ]
}

srcフォルダに子供コンポーネントを用意。

Child.vue
<template>
  <div>
    <div>Child</div>
    <div>{{ name }}</div>
    <div>{{ message }}</div>
  </div><br>
</template>

<script lang="ts">
export default {
  name: "Child",
  props: [
      "name",'message'],
}
</script>

<style scoped>
</style>

App.vueを変更します。

App.vue
<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <div v-for="item in items" :key="item">
    <Child v-bind:message="item.message" v-bind:name="item.name"></Child>
  </div>
</template>

<script lang="ts">
import {Options, Vue} from 'vue-class-component';
import Child from "@/Child.vue";
@Options({
  components: {
    Child
  },
  data() {
    return {
      items: [],
    }
  },
  methods:
      {
        load: function () {
          console.log("load start")
          fetch('./data.json')
              .then(response => {
                return response.json();
              })
              .then(json => {
                this.items = json.data;
                setTimeout(() =>
                {
                  console.log("reload start")
                  this.load();
                } , 1000)
              })
        }
      },
  mounted() {
    this.load();
  }
})
export default class App extends Vue {
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

まとめ

思ったより、参考サイトがすくなかった。
なんか間違った使い方なのかな。
それとも当たり前過ぎて、サイトにまとめないのか。
不安。

Git

vue-ts-load-interval
https://github.com/kawamurashin/vue-ts-load-interval/

参考

リストレンダリング
https://jp.vuejs.org/v2/guide/list.html

1
1
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
1