0

I am trying to set an data from a method. I am using fetch to get an rest data. But, when I try to set the data, using this.item = 'test' doesn't work. So, when my this.item is inside ".then" doesn't working. But when is out of ".then" it working... But I need to use a rest call to get the data...

Vue.component('internal_menu', {
   props: ['list'],
   data: function () {
      return {
         item: '1'
      }
   },
methods: {
   teste(event)
   {
       event.preventDefault();
       var payload = {
           method: 'GET',
           headers: { "Accept": "application/json; odata=verbose" },
           credentials: 'same-origin'    // or credentials: 'include'  
       }
       const url = _spPageContextInfo.webAbsoluteUrl + 
       "/_api/Web/Lists/GetByTitle('"+ this.list +"')/Items? 
       $select=Title,Id,Link,Icone&$orderby=Title%20asc";
       fetch(url,payload)
          .then((resp) => resp.json())
          .then(function(data) 
          {
              let items = data.d.results;
              this.item = 'teste';// this not working here
          })
        . catch(function(error) {
             console.log(JSON.stringify(error));
          });
          this.item = 'tst123'; //this working here
     },

 },
 template: `
    <div id='tst'>
       <h3>{{list}} - {{item}}</h3>
        <button v-on:click="teste">Try Me</button>
    </div>
`,
 mounted: function () {
    this.getMenuData();
 }
})

new Vue({
   el: "#app"
})

thanks Everton

1
  • 1
    I resolved my problem. I created an var self and get 'this' before to enter in callback. Commented Jan 8, 2019 at 3:28

1 Answer 1

1

When you do this:

.then(function(data) 
      {
          let items = data.d.results;
          this.item = 'teste';// this not working here
      })

Your closure's reference to this is the within the context of the anonymous function. Instead, you need to use the fat arrow function in order to maintain the context of the Component.

.then((data) => {
    let items = data.d.results;
    this.item = 'test';
})
Sign up to request clarification or add additional context in comments.

2 Comments

I initially thought it was an async/await issue but I do not see where is he calling the teste() method.
@RuChernChong In the click function of the button in the template.

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.