I am playing around with Vuejs in our project. I have used the same technique in my other project and its working. But here I am not able to assign the data return by the fetch request to a json resource.
When I try to access data returned in then and put it in alert it does gives me the data objects. but I want to assign it to my data attribute packages array.
Here is my component code
<template>
<div id="packages">
<div class='radio' v-for="package in packages">
<label>
<input type='radio' name='packageradio' v-bind:value="package.id">{{ package.quantity }}
<span id='price-tag'>{{ package.price }}</span>
</label>
</div>
</div>
</template>
<script>
export default {
data(){
return {
packages:[]
}
},
created(){
this.fetchPackages();
},
methods: {
fetchPackages: function(){
fetch('/die-cut/size/4/packages')
.then(res => res.json())
.then(function(res){
alert("i am hit");
this.packages = res;
})
.catch(err => console.log(err));
}
}
}
</script>
This is the api:
[
{
"id": 1,
"quantity": 50,
"price": 400,
"saving": 100,
"size_id": 4,
"sticker_id": 2,
"created_at": "2018-02-21 17:48:46",
"updated_at": "2018-02-21 17:48:46"
},
{
"id": 2,
"quantity": 100,
"price": 900,
"saving": 100,
"size_id": 4,
"sticker_id": 2,
"created_at": "2018-02-21 17:50:43",
"updated_at": "2018-02-21 17:50:43"
}
]
The data for packages should be working fine. The problem I see in your code is with the following html:
From the documentation for the label element:
So, in your code having
input
a flow content is the key issue.The issue with your code is:
Replace it with this:
I think its to do with your this keyword so, either use the ES5 syntax or do some thing like this
Or off course you can go ahead and do something like this,