iT邦幫忙

0

Nuxtjs 使用Axios 呼叫API 並且每秒鐘刷新一次

  • 分享至 

  • xImage

如題,我剛接觸Ven這種前端架構,剛好一個禮拜
目前我已經成功用Axios呼叫我自建的API,並且把資料放到echarts裡面
但想要在嘗試每秒鐘刷新一次數據(圖表),就卡住了,因為想到async asyncData() {}
是在頁面加載前呼叫,Axios好像用不能放在methods:{}
可以請教各位高手來幫我開示一下嗎@@

附上目前的程式碼:

<template></template>
  <v-app>
    <div>
      <v-card>
        <v-responsive :aspect-ratio="16 / 9">
          <v-card-text>
            <div id="test-charts" style="width:100%;height: 500px"></div>
            <div>現在時間:<span></span></div>
          </v-card-text>
        </v-responsive>
      </v-card>
    </div>
  </v-app>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";
export default {
  name: "DataScrapingPage",
  head: {
    title: "數據監測",
    meta: [
      { charset: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      {
        hid: "description",
        name: "description",
        content: "Official Nuxt.js starter for CodeSandBox"
      }
    ],
    link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }]
  },
  async asyncData({ params }) {
    const { data } = await axios.get(`http://192.168.0.173:8080/camera`);
    // console.log(Object.values。(data));
    const cameraname = [];
    const camerauid = [];
    const cameraFps = [];
    const test = Object.values(data);
    test.forEach(function (item) {
      cameraname.push(item.name);
      camerauid.push(item);
      cameraFps.push(item.fps);
    });
    return {
      tab: null,
      title: data[0].name,
      uid: data[0].uid,
      items: cameraname,
      text: camerauid,
      fps:cameraFps
    };
  },
  data() {
    return {};
  },
  mounted() {
    this.drawBar();
    setInterval(function () {
      this.drawBar();
    }.bind(this), 3000);
  },
  methods: {
    drawBar() {
        var chartDom = document.getElementById('test-charts');
        var myChart = echarts.init(chartDom);
        var option;
        console.log(this.items);
        var dataArray = this.items;
        var dataFps = this.fps;
      option = {
        xAxis: {
          type: "category",
          data: dataArray,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: dataFps,
            type: "line",
          },
        ],
      };
      
      option && myChart.setOption(option);
    },
  },
};

</script>

<style>
</style>
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
Eason Chiu
iT邦新手 4 級 ‧ 2022-12-08 08:24:28
最佳解答

當然可以在 method 啊,也可以在 mounted

mounted() {
    this.$axios(
        this.$globalconfig.apiUrl
    ).then((res) => {

另外也可以客製化 axios 寫在 plugin,之後就能用 this.$backAxio 呼叫

import axios from 'axios'
import Vue from 'vue'

Vue.prototype.$backAxio = axios.create({
    baseURL: process.env.api_url
})

我要發表回答

立即登入回答