'How to store data from an API with Vue and axios into variable that can be use on another library like chart.js

I am trying to store data from an API into a variable with Vue and axios but when I try to show the variable using document.write(this.info) it only show undefined, how to make that variable contain data from the API

Here is the photo example :

enter image description here

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.25.0/axios.min.js" integrity="sha512-/Q6t3CASm04EliI1QyIDAA/nDo9R8FQ/BULoUFyN4n/BDdyIxeH7u++Z+eobdmr11gG5D/6nPFyDlnisDwhpYA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="cpuHead">
  <div v-if="!infoCpu">loading ...</div>
  {{ infoCpu }}
</div>



    <script type="text/javascript">
    const newCpu = new Vue({
el: '#cpuHead',
data () {
  return {
    infoCpu: null
  }
},
async mounted () {
  await axios
    .get('http://192.168.20.98:9090/api/v1/query?query=process_cpu_seconds_total')
    .then(response => {
      this.infoCpu = response.data.data.result[0].value[1]
      console.log(this.infoCpu)
    })
    .catch((error) => {
      this.infoCpu = error.message
      console.log(error)
    })
}
})
    </script>

    <script type="text/javascript">
      document.write(this.infoCpu);
    </script>

  </body>
</html>


Solution 1:[1]

this inside your Vue instance points to newCpu instance and this outside of Vue instance points to global window object. Hence,

document.write(this.infoCpu); will try to find the infoCpu inside window object and will not able to find. Hence, resulting undefined.

Example :

const newCpu = new Vue({
  el: '#app',
  data: {
    message: null
  },
  async mounted () {
    this.message = 'Hello vue.js!';
    console.log(this); // Points to vue instance
  }
})

console.log(this); // Points to window object
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p>{{ message }}</p>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rohìt Jíndal