got property undefined when fetching data in ajax using vue.js - javascript

I have got a undefined when I alert the param fetching from ajax using vue.js, here is my code.
test.json return:
[
{isActive: false,name: test}
]
js:
new Vue({
el: '#viewport',
data: {
test_data: []
},
mounted: function () {
this.fetchTestData();
},
methods: {
fetchTestData: function () {
$.get(test.json, function (data) {
this.test_data = data;
alert(this.test_data.isActive);
});
}
}
});
I am beginner of vue.js, hope have a reply, thanks.

If you are fetching this data from that test.json file,
first it need to be like that because that's not validate json:
[
{
"isActive": false,
"name": "test"
}
]
and you need to use bind because this not referring to the Vue instance
fetchTestData: function () {
$.get('test.json', function (data) {
this.test_data = data;
alert(this.test_data[0].isActive);
}.bind(this));
}
and accessing the data like that this.test_data[0].isActive because it's an array

Related

Laravel 5.5 + Vue.js 2.x Proper API requests

I am working locally on a Laravel 5.5 project which uses Vue.js 2.5.9 on with XAMP Server.
I have to load some information to the DOM and refresh it when click "Refresh" button.
Sometimes the information is loaded and well displayed but sometimes they are not (some of the responses are):
Error 429: { "message": "Too Many Attempts." }
Error 500: { "message": "Server Error." }
I managed to "solve" the first issue (error 429) by increasing the Middleware throttle in Kernel.php from 'throttle:60,1', to 100,1)
But the second error I am not sure why I am get it sometimes and sometimes not.
I have this in my APIController (for example):
public function users()
{
$users = User::all();
return response()->json($users);
}
Then in app.js I call the methods in the created hook like this:
const app = new Vue({
el: '#app',
data: {
...
totalUsers: 0,
...
},
created: function() {
...
this.loadUsers();
...
},
methods: {
...
loadUsers: function() {
axios.get('/api/admin/users')
.then(function (response) {
app.totalUsers = response.data.length;
});
},
refreshData: function() {
this.loadUsers():
},
...
}
});
Maybe should I replace $users = User::all() to $users = User::count() to avoid loading "too much data" in API requests?
I think you should be using mounted() instead of created() in your vue.
const app = new Vue({
el: '#app',
data: {
...
totalUsers: 0,
...
},
mounted: function() {
...
this.loadUsers();
...
},
methods: {
...
loadUsers: function() {
axios.get('/api/admin/users')
.then(function (response) {
app.totalUsers = response.data.length;
});
},
refreshData: function() {
this.loadUsers():
},
...
}
});
that's the equivalent of the $(document).on(ready) in jQuery. Thats the method that fires when the window has fully loaded.
On a side note, Laravel knows when it is returning json as an ajax response, so you could probably just amend you controller method to this
public function users()
{
return User::all();
}

Trying to access an API using Vue js

I'm having some trouble trying to access an API to get or fetch data. I'm still currently new to vue.js and javascript. I'm getting an error Uncaught SyntaxError: Invalid shorthand property initializer. I can't seem to understand what the error means or seems to indicate.
<body>
<div id="vue-app">
{{ articles }}
</div>
<body>
var article = new Vue({
el: '#vue-app',
data: {
articles = ''
},
created: function () {
this.fetchData();
},
methods: {
fetchData: function () {
var that = this
this.$http.get('localhost/aim-beta/rest/export/json/article'),
function (data) {
vm.articles = data.main.temp;
}
}
}
});
Instead of using this.$http, use axios library for making api calls.
I think you can't use equal in the JS object syntax
data: {
articles = ''
}
Try
data: function() {
return () {
articles: ‘’
}
}
And specify http:// to the localhost
this.$http.get('http://localhost/aim-beta/rest/export/json/article'),
function (data) {
this.articles = data.json()
}
Use this for the data JSON object:
data: {
articles: ''
}
Then, use Promise for firing the HTTP request (note that I used the http:// with the URL):
this.$http.get('http://localhost/aim-beta/rest/export/json/article')
.then(function(response){
this.articles = response.json();
});
Source : Documentation

Vuejs form submit not working

I want to submit the values in my form but each time I press the submit button I get the following error:
Uncaught TypeError: login is not a function
at Object.submit [as fn] (eval at Yr (vue.min.js:7), <anonymous>:2:369)
at HTMLFormElement.<anonymous> (vue.min.js:6)
In my HTML code I have my form declared as such: <form v-on:submit.prevent="login">
In the JS it looks like this:
// register
Vue.component("login-form",
{
template: // THE HTML FORM
,
data: function () {
return data;
},
ready: function () {
this.isAuthenticated = this.checkIfAuthenticated();
this.userName = localStorage.getItem("id_name");
},
methods: {
checkIfAuthenticated: function () {
const users = [
{
id: 1,
name: "tom"
},
{
id: 2,
name: "brian"
},
{
id: 3,
name: "sam"
}
];
this.$set("users", users);
},
login: function () {
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
$.ajax({
url: "/token",
type: "post",
data: `username=${this.login.username}&password=${this.login.password}`,
headers: headers,
success: function (data) {
console.info(data);
},
error: function() {
this.isValid = false;
}
});
}
}
});
// create a root instance
var vue = new Vue({
el: "#loginForm"
});
As you see the login function is in my methods, so I don't see why vue is throwing the error
Edit: inluced a JSFiddle. The problem happens when you submit the form (after you click on login)
Looks like your instance has a conflict. There is a login property in a component and there is a login method in Vue instance. Try to use different names. Issue at vuejs github:
Both data properties and methods will be set on the instance, so the
short answered is: don't use conflicting names :)

Import json in backbone View

I'm new to backbone, and I'm still getting used to the flow of everything.. What I'm trying to do is import data.json file in my Model and make use of it in my view...
data.json
[
{ id: "001", student: "Mark" },
{ id: "002", student: "Sally" },
{ id: "003", student: "Harold" }
]
assets/data.js (model)
var DataModel = Backbone.Model.extend({
url: 'assets/data.json',
initialize: function() {
// this logs properly
console.log('this initializes');
}
})
data_view.js
var Students = Backbone.View.extend({
initialize: function() {
var data = new DataModel();
data.fetch();
// doesn't return json
console.log(data);
}
})
data logs like so...
v __proto__: Backbone.Model
> constructor: ()
> initialize: ()
url: "assets/data.json"
> __proto__: Object
All of my imports are correct, but why isn't my json loading within my view? What am I doing wrong? (I've tried making a collection, but that had the same effect; no json to be found)
Because fetch is using jQuery Ajax, so it's async. If you log data immediately after calling fetch, the data is not pull from server. You should do as follow:
data.fetch({
success: function(model, response, options) {
console.log(model);
},
error: function() {
}
});
Link reference: http://backbonejs.org/#Model-fetch
With using JQuery:
var DataModel = new DataModel();
$.when(DataModel.fetch()).then(function() {
var students = new Students({model: DataModel });
});

How to set a timer with a Vue.js class

im just using Vue.js to updates posts on a site im messing around with, this is what ive got so far (im still learning javascript, and not too great at it)
[app.js]
var Vue = require('vue');
Vue.use(require('vue-resource'));
var app = new Vue({
el: '#app',
components: {
'postlist' : require('./components/postlist/postlist.js')
}
});
[postlist.js]
module.exports = {
template: require('./postlist.template.html'),
data: function () {
return {
'search': '',
'posts' : {}
}
},
methods: {
'updatePosts' : function()
{
this.$http.get('api/posts', function(responce, status, request)
{
this.$set('posts', responce.data);
});
}
}
};
What I'm looking for is to have updatePosts fire off every x seconds, how do I do this?
ive tried doing this in the app.js
setInterval(function()
{
app.components.postlist.methods.updatePosts(); // doesnt work
app.postlist.updatePosts(); //doesnt work either
}, 500);
and tried putting the setInterval into the component itself
im pretty lost with this, whats the best way to achieve this?
updatePosts running every x seconds?
I have also trouble with scopes in Vue.
this should work
module.exports = {
template: require('./postlist.template.html'),
data: function () {
return {
'search': '',
posts: {}
}
},
methods: {
updatePosts: function () {
var self = this;
self.$http.get('api/posts', function(responce, status, request) {
self.posts = responce.data;
setTimeout(function(){ self.updatePosts() }, 2000);
});
}
},
created: function () {
this.updatePosts();
}
}
Functions in Vue works kinda different way, because your method updatePosts is not regular function. It is function defined in $vm.methods object. so It can't be called regularly like setTimeout($vm.updatePosts). Actually $vm.updatePosts doesn't exists. if you called it like $vm.updatePosts() it is different story. $vm instance automatically calls its method... So correct way is setTimeout(function(){ self.updatePosts() },2000)
You could start the request cycle in created or somewhere else in the lifecycle. It's also probably better to use recursion here so you can wait for the response to come back before you send off another one. I didn't test this code fully but it should work.
module.exports = {
template: require('./postlist.template.html'),
data: function () {
return {
'search': '',
posts: {}
}
},
methods: {
updatePosts: function () {
this.$http.get('api/posts', function(responce, status, request) {
this.posts = responce.data;
setTimeout(this.updatePosts, 2000);
});
}
},
created: function () {
this.updatePosts();
}
}

Categories

Resources