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.

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.