Vue JS Reload Button not working (v-on:click) - javascript

After struggling hours to implement a simple AJAX Call, I am now struggling with a reload button. As far as I can see the syntax is v-on:click="functionName".
In my case the Method I want to use is fetchData so -> v-on:click="fetchData".
However it does Nothing.
This is my vue Code:
<script>
var url = '{{ route('getAllFiles') }}';
new Vue({
el: '#fileTable',
data: {
files: [],
filesAreReady: false
},
created: function(){
this.fetchData();
},
methods: {
fetchData: function(){
var self = this;
self.filesAreReady = false;
self.files = [];
$.get(url, function(data){
self.files = $.parseJSON(data);
self.filesAreReady = true;
});
}
}
});
</script>
This is what PhpStorm tells me about v-on:
I'm using the latest version of Vue through the UNPKG.com CDN.

Related

Laravel and VueJS, access Vue instance.

I want to change a data property and run a method on my Vue instance within Laravel. However due to using webpack and laravel I can't seem to access the instance how I would expect to:
So window.app doesn't appear to be the correct instance of my Vue class.
Below is the Blade View i'm loading, as you can see I append a script tag to my main layout.blade.php, simply trying to change the Vue instance data property, and run a method.
#push('scripts')
<script>
app.unsaved = true;
app.triggerEvent(null, 'models', null);
</script>
#endpush
Below is part of my app.js (resources/assets/js/app.js):
const app = new Vue({
el: '#app',
components: {
'models-select': ModelsSelect
},
data: {
showModel: false,
unsaved: false
},
mounted: function() {
let _self = this;
(function() {
document.querySelectorAll("input, textarea, select").forEach(function(e) {
e.addEventListener('change', function() {
_self.unsaved = true;
e.classList.add('is-changed');
});
});
function unloadPage(){
if (_self.unsaved) return 'You appear to have un-saved changes!';
}
window.onbeforeunload = unloadPage;
})();
},
methods: {
triggerEvent: function(event, target, property)
{
app.$refs[target].update(event, property);
}
As you can see i'd expect to manipulate the Vue instance through the global app variable I have defined within the app.js. However this doesn't appear to be the case.
I get the following error when running the triggerEvent method:
app.triggerEvent is not a function
In your app.js file, change const app = new Vue({ to window.app = new Vue({.
Then within your <script> tags, change it to this.
<script>
window.app.unsaved = true;
window.app.triggerEvent(null, 'models', null);
</script>

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

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();
}
}

Confused with Backbone.js Paginator

I am trying to introduce pagination using the backbone.js paginator plugin's requestPager.
Problem: After setting up the collection which extends Backbone.Paginator.requestPager, I refreshed the webpage and the javascript console threw the error:
Uncaught TypeError: Object function (a){return new m(a)} has no method 'result' backbone.paginator.js:678
I am very new to backbone and is not sure what went wrong. Is it because I used fetch(), which showed up in the screenshot of the error below? I also noticed that no GET requests were sent to the backend. What happened, and how should I fix this? Thanks!
JS code
// Collection
window.ListingCollection = Backbone.Paginator.requestPager.extend({
model: Listing,
paginator_core: {
type: 'GET',
dataType: 'jsonp',
url: 'api/listings'
},
paginator_ui: {
firstPage: 0,
currentPage: 0,
perPage: 10,
totalPages: 10
},
server_api: {
'$filter': '',
'$per_page': function() { return this.perPage; },
'$current_row': function() { return this.currentPage * this.perPage; },
'$order_by': 'listing_id'
},
parse: function(response){
this.totalPages = Math.floor(response.total_rows / this.perPage);
}
});
JS Code
// Router
var AppRouter = Backbone.Router.extend({
routes: {
'': 'listings',
'listings': 'listings'
},
listings: function() {
var self = this;
// Load initial search results
this.listingList = new ListingCollection();
this.listingList.fetch({
success: function() {
self.listingListView = new ListingListView({ model: self.listingList });
$('#listing_list table').append(self.listingListView.render().el);
}
});
this.listingFilterView = new ListingFilterView();
}
});
Screenshot of Error in Javascript Console
JS Includes
<!-- JavaScript -->
<script src="assets/js/lib/jquery-1.7.1.min.js"></script>
<script src="assets/js/lib/underscore-min.js"></script>
<script src="assets/js/lib/backbone-min.js"></script>
<script src="assets/js/lib/backbone.paginator.js"></script>
<script src="assets/js/lib/bootstrap.js"></script>
<script src="assets/js/lib/bootstrap-datepicker.js"></script>
<script src="assets/js/app.js"></script>
You are probably using older version of Underscore. I use 1.3.1 and it does not have result() method. Download their new production version 1.3.3 - it has result().

Categories

Resources