How to instant data refresh with Laravel and vue.js? - laravel

I work with constantly changing api data. I use Laravel and Vue.js. There is a steady stream of data when I control the network with F11. But it has no effect on the DOM.
Here are sample codes. I would be glad if you help.
HTML code;
<div class="row">
<div class="col-md-12">
<p class="tv-value" v-html="totalMeetings"></p>
</div>
</div>
Script Code;
<script>
export default {
data() {
return {
totalMeetings: null
}
},
created() {
this.getPosts();
},
methods: {
getPosts() {
axios
.get("/get-total-meetings")
.then(response => (this.totalMeetings = response.data))
.catch(error => {
this.errors.push(error);
});
}
},
mounted() {
setInterval(function () {
axios
.get("/get-total-meetings")
.then(response => (this.totalMeetings = response.data))
.catch(error => {
this.errors.push(error);
});
}, 2000)
}
}
</script>

Change your setInterval function to arrow function like this.
setInterval(() => {
axios
.get("/get-total-meetings")
.then(response => (this.totalMeetings = response.data))
.catch(error => {
this.errors.push(error);
});
}, 2000);
You could put a watcher for that to be able vue to watch the changes of your data. like this.
watch: {
totalMeetings(val) {
this.totalMeetings = val
}
}
Or create a computed property for it to update the value when it changes.
computed: {
total_meetings() {
return this.totalMeetings
}
}
then your component should look like this
<p class="tv-value" v-html="total_meetings"></p>

Related

Allow HTML Tags Through Axios Request from Vue to Laravel Controller

I have a text area as below:
<textarea class="from-control" name="body" id="body" v-html="pageForm.body" v-model="pageForm.body" rows="5" style="width:100%"></textarea>
Script:
<script>
export default {
components: {},
data() {
return {
pageForm: new Form({
body: '',
}),
};
},
props: [],
mounted() {
},
methods: {
update() {
let loader = this.$loading.show();
this.pageForm.patch('/api/frontend/google-map/')
.then(response => {
toastr.success(response.message);
loader.hide();
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
});
},
}
}
</script>
I am sending an <iframe> from the <textarea> via axios patch request as <iframe src="some url"></iframe>
But in the laravel controller I receive $request->body = ""
Any ideas how do I achieve this?
Note:Form binding is working fine, but get empty value in Laravel Controller

How can I update my VueJs Data function properties value while fetching data from API using axios?

I have successfully fetched data from API. The fetched data shows in the alert function. However, the properties in the data function such as - 'Recovered' is not updating. I can show the fetched data using Vanilla JS. But I want to update them automatically and want to show them like this {{Recovered}}.
How can I do it??
<template>
<div class="container">
<h2>Total Recovered: {{Recovered}}</h2>
</div>
</template>
<script>
import axios from 'axios'
export default {
name:'CoronaStatus',
data: function () {
return {
Recovered: '',
TotalConfirmed: '',
TotalDeaths: '',
// test: '30',
// test_2: 'maheeb',
// componentKey: 0,
}
},
mounted(){
this.globalStatus();
},
methods:{
globalStatus: function(){
// const self = this;
// this.componentKey += 1;
axios.get('https://api.covid19api.com/summary')
.then((response) => {
// this.recovered = response.data.Global.NewConfirmed;
this.Recovered= response.data.Global.TotalRecovered;
alert(this.Recovered);
// document.getElementById('test_5').innerHTML = "total: " + this.TotalRecovered;
}).catch(err=> console.log(err));
},
}
}
</script>
<style scoped>
</style>
The easiest solution would be to refetch the information every hour with setInterval.
The best solution would be to use the WebHook provided by covid19api.com.
Vue.config.devtools = false;
Vue.config.productionTip = false;
var app = new Vue({
el: '#app',
data: {
Recovered: "Loading ..."
},
mounted() {
setInterval(() => {
this.globalStatus();
}, 3600000); // Call globalStatus every hour
this.globalStatus();
},
methods: {
globalStatus: function() {
axios
.get("https://api.covid19api.com/summary")
.then(response => {
this.Recovered = response.data.Global.TotalRecovered;
})
.catch(err => console.log(err));
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<div id="app">
<h2>Total Recovered: {{ Recovered }}</h2>
</div>

deleting specific comment that is attached to post vue laravel

I am currently creating a website with laravel and i created a comment system with vue. I managed to post comments successfully but i am having a problem with editing and deleting a specific comment. I am trying to somehow retrieve the id of each comment so i can create a method similar to the postComment() i have in the picture below to delete or edit the specific comment. Does anyone have an idea how to do that?
Thanks in advance
This is my post page which has the post and the attached comments
<script>
const app = new Vue({
el:'#root',
data: {
comments: {},
commentBox: '',
post: {!! $post->toJson() !!},
user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!},
},
mounted() {
this.getComments();
},
methods: {
getComments(){
axios.get('/api/posts/'+this.post.id+'/comments')
.then((response) => {
this.comments = response.data
})
.catch(function (error) {
console.log(error);
});
},
postComment(){
axios.post('/api/posts/'+this.post.id+'/comment', {
api_token: this.user.api_token,
text: this.commentBox
})
.then((response) => {
this.comments.unshift(response.data);
this.commentBox = '';
})
.catch(function (error) {
console.log(error);
});
},
}
});
</script>
In order to edit or delete a comment. You need the id of that comment. I create a very rough UI below for deleting. Updating requires a bit more complicated handling, but you get the idea:
<ul>
<!-- If the comments is an object, pls use Object.values(comments) -->
<li v-for="comment in comments">{{comment.text}} <button #click="deleteComment(comment.id)">Delete</button>
</ul>
<script>
const app = new Vue({
// ...
methods: {
deleteComment(commentId) {
// ...
}
}
});
</script>
You have to use the PUT request for upating and Delete for deleting data. I edited your code.
<script>
const app = new Vue({
el:'#root',
data: {
comments: {},
commentBox: '',
post: {!! $post->toJson() !!},
user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!},
},
mounted() {
this.getComments();
},
methods: {
deleteComments(){
axios.delete('/api/posts/'+this.post.id+')
.then((response) => {
console.log('Success")
})
.catch(function (error) {
console.log(error);
});
},
updateComment(){
axios.put('/api/posts/'+this.post.id, this.comments)
.then((response) => {
console.log('Success")
})
.catch(function (error) {
console.log(error);
});
},
}
});
</script>
I believe your back-end delete api route is api/posts/{post}

Laravel 5.7 - How to retrieve data from an API with a axios.get?

I'm trying to get data from an API in a Laravel Vue component.
I get this error in the console:
TypeError: Cannot set property 'continents' of undefined
What am I missing?
This is my code:
<script>
export default {
mounted() {
console.log('Component mounted.');
},
created(){
this.loadData();
},
data() {
return {
continents: [],
}
},
methods: {
loadData: function() {
axios.get('/api/continents')
.then(function (response) {
// handle success
console.log(response.data);
this.continents = response.data;
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
},
},
}
</script>
Here is the simple working demo of axios.get request
var app = new Vue({
el: '#app',
data: {
users:[]
},
mounted(){
this.loadData();
},
methods:{
loadData:function(){
axios.get('https://jsonplaceholder.typicode.com/users').then(res=>{
if(res.status==200){
this.users=res.data;
}
}).catch(err=>{
console.log(err)
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<ol>
<li v-if="users.length>0" v-for="user in users">
{{ user.name }}
</li>
</ol>
</div>
In methods you have to use arrow functions syntax in callback functions, to keep your data property accessible.
When you declare the function with normal syntax, you add a "child scope" and this.components in your callback refers to "this" inside you callback function.
Change your method to:
loadData() {
axios.get('/api/continents')
.then((response) => {
// handle success
console.log(response.data);
//now this refers to your vue instance and this can access you data property
this.continents = response.data;
})
.catch((error) => {
// handle error
console.log(error);
})
.then(() => {
// always executed
});
},
You should use arrow function in your call as instance of this is not available in your .then function of promise.Hence try as below.
Read more about arrow functions here
.
methods: {
loadData: function() {
axios.get('/api/continents')
.then((response) => {
// handle success
console.log(response.data);
this.continents = response.data;
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
},
},

Vue js can't display data

My data from api I want to display is not working
[{"gameID":1368656,"gameReultTime":"2019-03-01 01:08:25","gameReult":2763.33,"totalPayout":1.98,"totalbet":100}]
display and there is no any data
<tr v-for="data in dataresults">
<td>{{data.gameID}}</td>
<td> {{ data.totalbet }}</td>
<td>{{data.gameReult}}</td>
<td>{{data.totalPayout}}</td>
</tr>
JS
data() {
return {
dataresults: [],
};
},
axios
.get("api/getoutcome")
.then((response) => {
this.dataresults = response.data
})
.catch(function(error) {
console.warn(error);
});
Please try to move your code for example to mounted lifecycle hook:
data() {
return {
dataresults: [],
};
},
mounted() {
axios
.get("api/getoutcome")
.then((response) => {
this.dataresults = response.data
})
.catch(function(error) {
console.warn(error);
});
}

Resources