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);
});
}
Related
im trying to get row cout but returning 0 only.
my code
<template>
<div>
<p>{{ resultCount }}</p>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
registerlist: [],
};
},
async asyncData({ $axios }) {
let { data } = await $axios.$get("/Businessregisterlist");
// console.log(response)
return {
registerlist: data,
};
},
computed: {
resultCount() {
return Object.keys(this.registerlist).length;
},
},
};
</script>
This is because when you return a property in asyncData, you should not have it in data property of the component instance, instead the later will override the returned with asyncData.
<script>
import axios from "axios";
export default {
async asyncData({ $axios }) {
let { data } = await $axios.$get("/Businessregisterlist");
// console.log(response)
return {
registerlist: data,
};
},
computed: {
resultCount() {
return Object.keys(this.registerlist).length;
},
},
};
</script>
<template>
<div>
<p>{{ resultCount }}</p>
</div>
</template>
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>
I created a component that can add additional fields by pressing a button. I don't know how would I submit this in the database with axios.post and laravel controller. I was able to achieve it in the past with the use of jquery and pure laravel, but I'm confused how to implement it in vue and axios.
Component.vue
<template>
<v-app>
<table class="table">
<thead>
<tr>
<td><strong>Title</strong></td>
<td><strong>Description</strong></td>
<td><strong>File</strong></td>
<td></td>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in rows" :key="row.id">
<td><v-text-field outlined v-model="row.title" /></td>
<td><v-text-field outlined v-model="row.description" /></td>
<td>
<label class="fileContainer">
<input type="file" #change="setFilename($event, row)" :id="index">
</label>
</td>
<td><a #click="removeElement(index);" style="cursor: pointer">X</a></td>
</tr>
</tbody>
</table>
<div>
<v-btn #click="addRow()">Add row</v-btn>
<v-btn class="success" #click="save()">Save</v-btn>
<pre>{{ rows | json}}</pre>
</div>
</v-app>
</template>
<script>
export default {
data: ()=> ({
rows: []
}),
methods: {
addRow() {
var elem = document.createElement('tr');
this.rows.push({
title: "",
description: "",
file: {
name: 'Choose File'
}
});
},
removeElement(index) {
this.rows.splice(index, 1);
},
setFilename(event, row) {
var file = event.target.files[0];
row.file = file
},
save() {
// axios.post
}
}
}
</script>
Controller.php
public function store(Request $request)
{
// store function
}
save() {
let data = this.rows
axios
.post("Url", {
data
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err)
});
}
ref link https://github.com/axios/axios
save() {
axios
.post("/your/uri", {
user_id: 1,
user_name:'jhone doe',
email:'test#test.com'
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error)
});
}
You can retrieve your data from your controller $request->user_id,...,$request->email
Tip: if you post any object,you must JSON.stringify(your_json) them and in a response data from controller json_decode($your_json,true) or you need to modify your header file.
Always use '/your/uri' instead of /your/uri/ without trailing '/'
It now works. I'll be posting my code just in case someone encounter the same hurdle. Than you very much to #kamlesh-paul and #md-amirozzaman
Component.vue
<script>
export default {
data: ()=> ({
rows: [],
}),
methods: {
addRow() {
this.rows.push({
corporate_objective_id: '',
kpa: '',
kpi: '',
weight: '',
score: '',
equal: '',
file: {
name: 'Choose File'
}
});
},
removeElement(index) {
this.rows.splice(index, 1);
},
setFilename(event, row) {
var file = event.target.files[0];
row.file = file
},
save() {
const postData = {
data: this.rows
}
console.log(postData)
axios
.post('/api/employee-objective', {postData})
.then(res => { console.log(res) })
.catch(err => { console.log(err) });
}
}
}
</script>
Controller.php
public function store(Request $request) {
foreach($request->data as $data) {
$container = EmployeeObjective::updateOrCreate([
'kpa_info' => $data['kpa'],
'kpi_info' => $data['kpi'],
'kpa_weight' => $data['weight'],
'kpa_score_1' => $data['score'],
'kpa_equal' => $data['equal'],
]);
$container->save();
}
}
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}
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
});
},
},