cari

Rumah  >  Soal Jawab  >  teks badan

Cara mengemas kini pembolehubah 'ini' dalam Vue.js dan menetapkan hasil API

Saya ingin mengemas kini pembolehubah saya nbeBugs 但在 then yang tidak boleh diakses dalam fungsi. Fungsi saya getApi ialah fungsi async kerana API mengambil masa untuk bertindak balas

template.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粉071626364P粉071626364521 hari yang lalu534

membalas semua(1)saya akan balas

  • P粉854119263

    P粉8541192632023-09-07 19:21:55

    Jika lulus ke .then() 函数的参数是常规函数,它有自己的作用域,并且在其内部,外部作用域的变量将无法使用 this 访问..

    Gunakan fungsi anak panah sebaliknya:

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

    Nota sampingan: Anda akan dikemas kini this.chartGitlab。要么将该更新移至 then() 内,要么在服务器请求前面使用 await sebelum permintaan kembali. Kemungkinan besar, ini akan berfungsi seperti yang diharapkan:

    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"],
            },
          ],
        };
      },
    }
    

    balas
    0
  • Batalbalas