Reputation: 27
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
Upvotes: 0
Views: 1491
Reputation: 50798
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';
})
Upvotes: 1