Basic vue.js 2 and vue-resource http get with variable assignment - javascript

I'm really struggling to get the most basic REST functionality to work in vue.js 2.
I'd like to get data from some endpoint and assign the returned value to a variable of my Vue instance. Here's how far I got.
var link = 'https://jsonplaceholder.typicode.com/users';
var users;
Vue.http.get(link).then(function(response){
users = response.data;
}, function(error){
console.log(error.statusText);
});
new Vue ({
el: '#user-list',
data: {
list: users
}
});
Inside the promise, I can access the response data, but I cannot seem to assign it to users or even to data of the Vue instance.
Needless to say, I'm completely new to vue.js and thankful for any help.
Stack: vue.js 2.03, vue-resource 1.0.3
Cheers!

You can create an object and pass it to the vue instance like that :
var link = 'https://jsonplaceholder.typicode.com/users';
var data = {
list: null
};
Vue.http.get(link).then(function(response){
data.list = response.data;
}, function(error){
console.log(error.statusText);
});
new Vue ({
el: '#app',
data: data
});
Or you can create a function under the methods object and then call it in the mounted function :
var link = 'https://jsonplaceholder.typicode.com/users';
new Vue ({
el: '#app',
data: {
list: null
},
methods:{
getUsers: function(){
this.$http.get(link).then(function(response){
this.list = response.data;
}, function(error){
console.log(error.statusText);
});
}
},
mounted: function () {
this.getUsers();
}
});

Related

How to return data from method in Vue.js?

I'm learning Vue.js, and I have trouble finding anything related to this topic. I fetch the data from the API, which shows in console.log correctly, but I can't seem to return it to the template view. I am not trying to send this data to another component; I want to display it. How do you make this happen? In React, I would map the result and return the HTML. How do you do this in Vue.js? Also, I am doing this in Laravel 8.
<template>
<div>
{{ data }}
</div>
</template>
<script>
let api = location.search.replace("?", "/");
api = api.replace("=", "");
export default {
name: "Play",
data: function () {
return {
data: data
};
},
created() {
this.getQuestions();
},
methods: {
getQuestions() {
let data = [];
fetch(api)
.then(response => response.json())
.then(response => {
return (data = response.results);
})
.catch(err => console.log(err));
}
}
};
</script>
To access a data property on a Vue component, you must use the this accessor:
this.data = response.results
What is data here?
data: function() {
return {
data: *data*
};
},
this data hasn't been declared anywhere, you need to set it to a default value, maybe a null like this,
data: function() {
return {
data: null
};
},
then try setting it in the method like this
this.data = response.data
and then you can access it in the template like the way you have done already.
Also, it is advised to use Vue's $set method to keep the reactivity flow - so you can use
this.$set(this, 'data', response.data);
to set the data.
change this
data: function() {
return {
data: data
};
to
data: function() {
return {
data: null
};
change creataed() to mounted()
add
this.data = response.results;
in your getQuestions() in place of your return(data = response.results);
I think you can also kill the
.then(response => response.json())
in your vue template you can do
<div>
<template v-if="data"> {{data.somefield}}<template>
</div>
The idea is you set data to null, when the component is mounted you "fetch" data and save it to the data property.
Vue sees that the data is no longer null and shows you data.somefield

Why is Vuejs not updating elements in time?

I am currently faced with a situation where I add options to a select element via vuejs when the #change of that specific element is called.
The problem is that the new option is not 'registered' until I leave the function.
I made a jsfiddle to demonstrate this behaviour: https://jsfiddle.net/bz8361Lp/
In this demo, if a option in the select element is selected, a new option is added to the select. The console is still printing the old number of entries.
new Vue({
el: "#app",
data: {
data: ["test", "hallo", "bye"]
},
methods: {
onChange(event) {
console.log("test")
this.data.push("hello")
const element = document.getElementById("select")
console.log(element.options.length)
}
}
})
I am looking for some guidance on how I can avoid this problem, what I am doing wrong and what a best practice could be.
Thanks.
This is because Vue.js updates DOM not immediately but on the next event loop processing.
You can read about this in detail here
You can check this by using nextTick:
onChange(event) {
console.log("test")
this.data.push("hello")
this.$nextTick(() => {
const element = document.getElementById("select")
console.log(element.options.length)
});
}
need to wait for the dom to render and then evaluate. You can find more information about what the function does '' this.$nextTick()
new Vue({
el: "#app",
data: {
data: ["test", "hallo", "bye"]
},
methods: {
onChange(event) {
console.log("test")
this.data.push("hello")
this.$nextTick(() => {
const element = document.getElementById("select")
console.log(element.options.length)
})
}
}
})

How to write data from an AJAX request to DATA in VUE JS?

Tell me please, how in DATA to write data from the AJAX response?
Example:
var example = new Vue({
el: '#example',
data:{
myArr: []
},
created: function () {
$.getJSON('data.json', function(data) {
this.myArr = data;
});
}
});
The problem is that in myArr, the response data is not written. How to solve this? Thank you.
Can you try this ? Basically this inside the ajax is not exactly the one you would expect.
var example = new Vue({
el: '#example',
data:{
myArr: []
},
created: function () {
var vm = this;
$.getJSON('data.json', function(data) {
vm.myArr = data;
});
}
});
You can also use reactivity setting method $set instead of directly assigning to the vm.myArr : https://v2.vuejs.org/v2/guide/reactivity.html

Manipulating the data value in Vue.js

How can I set the value of name to the property personOne in object? So that name will have the value of Alex.
var app = new Vue({
el: '#app',
data: {
name: '',
object: { "personOne": "Alex", "personTwo": "Jack"}
}
})
From within the Vue object you write
this.name = 'Alex' and outside you write app.name = 'Alex'
app.someDataField will change the data property called someDataField
You can use one of the life-cycle hooks like created created or mounted for setting initial data, loading data from API, etc, like following:
var app = new Vue({
el: '#app',
data: {
name: '',
object: { "personOne": "Alex", "personTwo": "Jack"}
},
methods: {
setName (name) {
this.name = name
}
},
mounted () {
this.setName(this.object.personOne)
},
})

Backbone parse server response to model

I'm trying to deal with a server response, and am a little confused how to turn the json response into Backbone Models.
My Backbone model looks like so:
Entities.Recipe = Backbone.Model.extend({
defaults: {
id: '',
name: '',
introduction: ''
},
parse: function (response)
{
if(._isObject(response.results)){
return response.results
else {
return response
}
})
Entities.RecipeCollection = Backbone.Collection.extend({
url: 'recipes',
model: Entities.Recipe
)}
var API = {
getRecipeEntities: function (){
var recipes = new Entities.RecipeCollection()
var defer = $.Deferred()
recipes.fetch({
url: 'http://3rdpartyApilocation.com/recipes'
success: function (data) {
defer.resolve(data)
}
})
var promise = defer.promise()
$.when(promise).done(function (fetchedData)
{})
return promise
}
RecipeManager.reqres.setHandler('recipe:entities', function()
{
return API.getRecipeEntities()
}
And the response.results is an Array of objects - with each object having an id key, a name key and an introduction key. But because I am so inexperienced with Backbone I have no idea how to map those results to the model?
I have installed Chromes Marionette inspector and when I look at the entire array of results seems to be passed to the model, rather than each individual object within each response.result being set to each individual model. Sorry if I can't be more clear - I'm very new to Backbone...
Perhaps your confusion is because you're in fact able to use parse on a model or on a collection. And from your explanation it looks like the response.results object returns a list of objects that you want to become models in your application. But because you're catching that object in a model, the model doesn't know what to do with that array.
Let's say you have a response like this:
{
"status": "ok",
"results": [
{
"id": 1,
"name": "Pie"
}, {
"id": 2,
"name": "Rice"
}, {
"id": 3,
"name": "Meatballs"
}
]
}
Then you would just use parse on your Collection to let it know the response isn't array itself, and help it find it in the results property.
Here's a working example:
var Recipe = Backbone.Model.extend();
var Recipes = Backbone.Collection.extend({
model: Recipe,
url: 'http://www.mocky.io/v2/56390090120000fa08a61a57',
parse: function(response){
return response.results;
}
});
var recipes = new Recipes();
recipes.fetch().done(function(){
recipes.each(function(recipe){
/** Just demo of the fetched data */
$(document.body).append('<p>'+ recipe.get('name') +'</p>');
});
});
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>

Categories

Resources