如何在Vue.js中更新一個'this'變數並設定API結果
P粉071626364
P粉071626364 2023-09-06 20:36:30
0
1
505

我想更新我的變數 nbeBugs 但在 then 函數內無法存取。 我的函數 getApi 是 async 函數,因為 API 需要時間回應

模板.vue

<script>
import ChartDataLabels from 'chartjs-plugin-datalabels'
import getApi from '../../api/api'
const plugins = [ChartDataLabels]
    export default {
        data() {
        return {
            
            plugins: [ChartDataLabels],
            nbeBugs: [10,10,10,10,10],
            chartGitlab: null,
            lightOptions3: {
                plugins: {
                    legend: {
                        labels: {
                            color: '#ddd'
                        },
                        display: true,
                        position: 'bottom',
                        align: 'center'
                    },
                    datalabels: {
                        color: '#EEE',
                        labels: {
                            value: {
                            font: {
                                weight: 'bold',
                                size: 24,
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    mounted () {
         this.getData()       
    },
    methods: {
        getData() {
            let url_application = 'api/bugs_gitlab'
            
            getApi(url_application, null).then(function(results){
                console.log(results.data)
                this.nbeBugs = results.data
                })
            this.chartGitlab = {
                labels: ['Bloquant','Critique','Majeur','Moyen','Faible'],
                datasets: [
                    {
                        borderColor: "#071426",
                        data: this.nbeBugs,
                        backgroundColor: ["#FF6384","#36A2EB","#FFA726","#66BB6A","#a855f7"],
                        hoverBackgroundColor: ["#FF6384","#36A2EB","#FFA726","#66BB6A","#a855f7"]
                    }
                ]
            }
        }
    }
}
</script>

<template>
<div class="col-12 xl:col-6">
    <div class="card p-3 h-full">
        <h5>Nombre de bugs Gitlab</h5>
        <div class="flex h-full justify-content-center align-content-center flex-wrap card-container yellow-container">
            <Chart type="doughnut" :data="chartGitlab" :options="lightOptions3" :plugins="plugins"/>
        </div>
    </div>
</div>
</template>

<style scoped>
</style>

api.js

import axios from "axios";
let path = import.meta.env.VITE_API_URL;
const axiosObjet = axios.create({
    baseURL: path,
    timeout: 8000,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.apiToken
        }
  });

async function getApi(api_path, data) {
    //console.log(headers)
    console.log(path)
    //console.log(axiosObjet)
    try {
        let res = await axiosObjet.get(api_path)
        if(res.status == 200){
            // test for status you want, etc
            console.log(res.status)
        }
        
        // Don't forget to return something   
        return res
    }
    catch (err) {
        console.error("getApi error : " + err);
    }
}

export default getApi

P粉071626364
P粉071626364

全部回覆(1)
P粉854119263

如果傳遞給.then() 函數的參數是常規函數,它有自己的作用域,並且在其內部,外部作用域的變數將無法使用this 存取..

改用箭頭函數

getApi(url_application, null).then(({ data }) => {
  console.log(data);
  this.nbeBugs = data;
});

附註:您將在請求返回之前更新 this.chartGitlab。要麼將該更新移至 then() 內,要麼在伺服器請求前面使用 await。最有可能的是,這將按預期工作:

methods: {
  async getData() {
    let url_application = "api/bugs_gitlab";

    await getApi(url_application, null).then(({ data }) => {
      console.log(data);
      this.nbeBugs = data;
    });
    this.chartGitlab = {
      labels: ["Bloquant", "Critique", "Majeur", "Moyen", "Faible"],
      datasets: [
        {
          borderColor: "#071426",
          data: this.nbeBugs,
          backgroundColor: ["#FF6384","#36A2EB","#FFA726","#66BB6A","#a855f7"],
          hoverBackgroundColor: ["#FF6384","#36A2EB","#FFA726","#66BB6A","#a855f7"],
        },
      ],
    };
  },
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板