Vue not loading data - javascript

I have a vue/coffeescript app that looks like this:
There are no errors in the console, and it says it's making a successful external request for the JSON, however When I say {{book.name}}, it only returns as Test instead of coming from the JSON.
new Vue({
el: '#app',
data: {
showModal: false,
book: {
name: "Test",
description: "",
photo: ""
}
}
ready: () ->
this.getBookData()
console.log (this.book)
methods: {
getBookData: () ->
self = $(this)
$.getJSON 'GGPK4A.json', (data) ->
self.book = data
}
})

I don't know how to do it in coffeescript, but I think the issue is that this doesn't refer to Vue within the callback function, so setting this.book isn't working. Normally you can fix this using .bind(this) on the function, or setting var vm = this before the ajax call and setting vm.book in the callback.

Related

How to use vue-resource whit jsonp?

I'm trying to get data from this url,
http://opendata.euskadi.eus/contenidos/ds_recursos_turisticos/albergues_de_euskadi/opendata/alojamientos.json
which returns a jsonp, but I can not get them with vue-resource (with pure javascript, JQuery, and some other libary like fetch-jsonp, I get them).
Could someone please post an example?
this is my code
new Vue({
el: '.App',
mounted: function () {
this.cojerDatos()
},
data: {
losDatos: {}
},
methods: {
cojerDatos() {
const url = "http://opendata.euskadi.eus/contenidos/ds_recursos_turisticos/albergues_de_euskadi/opendata/alojamientos.json";
this.$http.jsonp(url,{params: {jsonCallback: 'jsonCallback'}})
.then(response => console.log(response.json()))
},
}
})
I note, moreover, that the url adds the parameters of a call to the random callback.
Thank you very much.

Vue JS v-for not iterating over array

Hi guys I am using Vue JS to try and loop through my data. Here is my whole JS file:
var contentful = require('contentful');
var client = contentful.createClient({
space: 'HIDDEN',
accessToken: 'HIDDEN'
});
Vue.component('careers', {
template: '<div><div v-for="career in careerData">{{ fields.jobDescription }}</div></div>',
data: function() {
return {
careerData: []
}
},
created: function() {
this.fetchData();
},
methods: {
fetchData: function() {
client.getEntries()
.then(function (entries) {
// log the title for all the entries that have it
entries.items.forEach(function (entry) {
if(entry.fields.jobTitle) {
this.careerData = entries.items;
}
})
});
}
}
});
var app = new Vue({
el: '#app'
});
I am using methods to access some data from Contentful, once it has grabbed the necessary data it is sent to my data object.
If I console.log(careerData); within my console the following data is returned:
So I'd expect if I used v-for within my template and tried iterating over careerData it would render correctly however on my front-end I am left with an empty div like so:
<div id="app"><div></div></div>
I am currently pulling my component into my HTML like so:
<div id="app">
<careers></careers>
</div>
No errors are displayed within my console, can you think of any reason this might be happening?
Thanks, Nick
Several problems I think. As #dfsq said, you should use a arrow function if you want to keep context (this).
fetchData: function() {
client.getEntries()
.then(entries => {
this.careerData = entries.items
});
}
Then you may replace {{fields.jobDescription}} by {{career.fields.jobDescription}}, as #unholysheep wrote.
It may work. If it does not, you could add a this.$forceUpdate(); right after this.fetchData();
Use arrow function in forEach callback so you don't loose context:
fetchData: function() {
client.getEntries()
.then(entries => {
this.careerData = entries.items
});
}

Language in VueJS from JSON

I am trying to load locale language variables from a JSON Request (laravel generated) to VueJS since VueJS does not support locale out of the box. The ready function alert does not alert but the random text data variable does work. I know VueJS is loading correctly. There are no console errors and webpack compiles the vue. The lang array says empty and the lang.email shows blank. This is my issue. Any help appreciated.
const app = new Vue({
el: '#app',
data: {
lang: [],
randomtext: 'This is Random Text'
},
ready: function() {
alert('THIS DOES NOT ALERT');
this.getLanguage();
},
methods: {
getLanguage: function() {
this.$http.get('/lang/auth').then((response) => {
this.$set("lang", response)
}, (response) => {
alert(response);
});
}
}
});
the 'lang/auth'
{"email":"Email Address","password":"Password"}
my html:
<h5 class="content-group">#{{ randomtext }}</h5> // This Works
<input type="text" class="form-control" :placeholder="lang.email"> // This does not
Indeed, "ready" was deprecated in Vue.js 2
Try using "mounted" instead.
First, Change ready: into mounted:
(Because, vuejs version 2 doesn't support it anymore)
Second, Instead of using this.$set use this.lang = response
Here is the full code
https://jsfiddle.net/uqp7f4zL/

How to implement a function when a component is created in Vue?

According to the docs, the constructor of the Vue object is managed like this.
var vm = new Vue({
created: function () { console.log("I'm created!"); }
});
However, I can't figure out how to do the corresponding thing when a Vue component is created. I've tried the following but don't get any print to the console.
export default {
created: function() { console.log("Component created!"); }
}
Is it possible to subscribe/listen to a component being rendered? I'd like to react to that event by downloading some data and putting it in the store, so that the table that the component carries will get its information to display.
In my applications, I tend to use the mounted hook to load up some Ajax data once the component has mounted.
Example code from my app:
Vue.component('book-class', {
template: '#booking-template',
props: ['teacherid'],
data: function () {
return{
// few data items returned here..
message: ''
}
},
methods: {
// Few methods here..
},
computed: {
// few computed methods here...
},
mounted: function () {
var that = this;
$.ajax({
type: 'GET',
url: '/classinfo/' + this.teacherid,
success: function (data) {
console.log(JSON.stringify(data));
}
})
}
});
new Vue({
el: '#mainapp',
data: {
message: 'some message here..'
}
});
However, I can also use created() hook as well as it is in the lifecycle as well.
In Vue2 you have the following lifecycle hooks:
components doesn't have life cycle hooks like app. but they has something similar. that fixed my problem:
https://v2.vuejs.org/v2/api/#updated

Not fetching correct url issue

I have a backboneJS app that has a router that looks
var StoreRouter = Backbone.Router.extend({
routes: {
'stores/add/' : 'add',
'stores/edit/:id': 'edit'
},
add: function(){
var addStoresView = new AddStoresView({
el: ".wrapper"
});
},
edit: function(id){
var editStoresView = new EditStoresView({
el: ".wrapper",
model: new Store({ id: id })
});
}
});
var storeRouter = new StoreRouter();
Backbone.history.start({ pushState: true, hashChange: false });
and a model that looks like:
var Store = Backbone.Model.extend({
urlRoot: "/stores/"
});
and then my view looks like:
var EditStoresView = Backbone.View.extend({
...
render: function() {
this.model.fetch({
success : function(model, response, options) {
this.$el.append ( JST['tmpl/' + "edit"] (model.toJSON()) );
}
});
}
I thought that urlRoot when fetched would call /stores/ID_HERE, but right now it doesn't call that, it just calls /stores/, but I'm not sure why and how to fix this?
In devTools, here is the url it's going for:
GET http://localhost/stores/
This might not be the answer since it depends on your real production code.
Normally the code you entered is supposed to work, and I even saw a comment saying that it works in a jsfiddle. A couple of reasons might affect the outcome:
In your code you changed the Backbone.Model.url() function. By default the url function is
url: function() {
var base =
_.result(this, 'urlRoot') ||
_.result(this.collection, 'url') ||
urlError();
if (this.isNew()) return base;
return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
},
This is the function to be used by Backbone to generate the URL for model.fetch();.
You added a custom idAttribute when you declared your Store Model to be like the one in your DB. For example your database has a different id than id itself, but in your code you still use new Model({ id: id }); when you really should use new Model({ customId: id });. What happens behind the scenes is that you see in the url() function it checks if the model isNew(). This function actually checks if the id is set, but if it is custom it checks for that:
isNew: function() {
return !this.has(this.idAttribute);
},
You messed up with Backbone.sync ... lots of things can be done with this I will not even start unless I want to make a paper on it. Maybe you followed a tutorial without knowing that it might affect some other code.
You called model.fetch() "a la" $.ajax style:
model.fetch({
data: objectHere,
url: yourUrlHere,
success: function () {},
error: function () {}
});
This overrides the awesomeness of the Backbone automation. (I think sync takes over from here, don't quote me on that).
Reference: Backbone annotated sourcecode

Categories