1

Given I have a component called upload-csv

Vue.component('upload-csv',{
 props:['clientnames'],
 template:`
    <ul>
       <li v-for="clientname in clientnames">{{ clientname.name }}</li>
    </ul>
 `
});

Then a Vue Instance

new Vue({
 el:"#upload-csv-component",
 data:{
  loadurl:'http://localhost/startup/public/index.php/loadnames',
  clientnames:[]
 },
 mounted:function(){
  axios.get(this.loadurl)
  .then(function(response){
   this.clientnames = response.data;
  })
  .catch(function(error){});
 }
});

Wish to use it this way

<div id="upload-csv-component">
  <upload-csv :clientnames="clientnames"></upload-csv>
</div>

But the list is not rendering; I have changed mounted hook to beforeMount yet the list is not rendering.

Please can someone suggest a way to solve this problem.

amachree tamunoemi
  • 817
  • 2
  • 16
  • 33

2 Answers2

4

Use an arrow function to keep access to this inside the axios request:

mounted(){
  axios.get(this.loadurl)
  .then((response) => {
    this.clientnames = response.data
  })
}

(great answer here about this context)

Sovalina
  • 5,410
  • 4
  • 22
  • 39
1

It would appear that axios requires the fat arrow syntax, as shown here
Using Axios to Consume APIs

console.clear();

Vue.component('upload-csv',{
 props:['clientnames'],
 template:`
    <ul>
       <li v-for="clientname in clientnames">{{ clientname.name }}</li>
    </ul>
 `
});

new Vue({
 el:"#upload-csv-component",
 data () {
   return {       
     loadurl:'https://jsonplaceholder.typicode.com/users',
     clientnames:[]
   }
 },
 mounted:function(){
  axios.get(this.loadurl)
  .then(response => {
   console.log(response);
   this.clientnames = response.data;
  })
  .catch(function(error){});
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="upload-csv-component">
  <h1>Clients</h1>
  <upload-csv :clientnames="clientnames"></upload-csv>
</div>
tony19
  • 125,647
  • 18
  • 229
  • 307
Richard Matsen
  • 20,671
  • 3
  • 43
  • 77