Home > Software design >  Using Axios return object inside script tag
Using Axios return object inside script tag

Time:04-29

I am using data from my API by using Axios and returning it in an array. I can access the data in the html section with a simple v-for but I also want to access the data inside the script section, is this possible? I kept trying to reference it, but I can't find the correct way to use it.

I need the data because I have a graph implemented in the view and the data for the graph is defined in the script section.

I'm working in an MVC 6 project in a .cshtml file. I already have controller function that can access data from the API and is accessible by referencing the model, but because I could only access one API endpoint per controller method, I wanted to implement Axios.

Code that i have used:

created() {
    axios.get('https://localhost:44332/api/clients')
    .then(response => { this.clients = response.data})
    .catch(error => {console.log(error)})}

Vue setup:

    let app = new Vue({
    el: '#app',data() {
    return {
    clients: []
    }},

Tech stack: Vue 2.6 with Axios, .NET 6 MVC

CodePudding user response:

If I understood you correctly, if you want data from vue you can use $data:

let app = new Vue({
  el: '#app',
  data() {
    return {
      clients: [],
    }
  },
  async created() {
    await axios.get('https://jsonplaceholder.typicode.com/users')
      .then(response => { this.clients = response.data})
      .catch(error => {console.log(error)})
  },
})
function getData() {
  setTimeout(() => console.log('outside of vue ', app.$data.clients), 500)
}
getData()
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id='app'>
  <div v-for="(client, i) in clients" :key="i">
    {{ client }}
  </div>
</div>

  • Related