i have 2 data from API
1. Category Food
2. Finish Good
how can i show 2 data from API in 1 page vue,
I only can show 1 data from API
this is what i tried
export default {
data(){
items:[],
finish_goods:[],
created() {
let uri = 'http://192.168.10.75:8000/api/finish_goods'; // Data 1
this.axios.get(uri).then(response => {
this.items = response.data.data;
});
},
created() {
let uri = 'http://192.168.10.75:8000/api/cat_foods'; // Data 2
this.axios.get(uri).then(response => {
this.finish_goods = response.data.data;
});
}
},
methods: {}
}
You're along the right lines, but it looks like your template syntax is a bit messed up...
// Make sure axios is installed via npm, you can skip this step
// if you've declared window.axios = axios somewhere in your app...
import axios from 'axios';
export default {
// Data must be a function that returns the initial state object...
data() {
return {
finishGoods: [],
catFoods: []
};
},
// Created is a hook and can only be defined once, think of it like an event listener...
created() {
let finishGoodsUri = 'http://192.168.10.75:8000/api/finish_goods';
// Fetch finish goods, note that I'm not calling this.axios...
axios.get(finishGoodsUri).then(response => {
this.finishGoods = response.data.data;
});
let catFoodsUri = 'http://192.168.10.75:8000/api/cat_foods';
// Fetch cat foods...
axios.get(catFoodsUri).then(response => {
this.catFoods = response.data.data;
});
}
}
Now in your template you can do the following:
<template>
<div>
<div v-for="finishGood in finishGoods">
{{ finishGood.attribute }}
</div>
<div v-for="catFood in catFoods">
{{ catFood.attribute }}
</div>
</div>
</template>
my advice, combine the API as 1
created() {
let uri = 'http://192.168.10.75:8000/api/combine_data'; // sample
this.axios.get(uri).then(response => {
this.finish_goods = response.data.data.goods;
this.items = response.data.data.foods;
});
}
Related
I'm working on getting data from API by performing api call with axios. But my attempts to get data from api aren't succesful. How to make it work?
export default {
mounted() {
this.fetchData()
},
data() {
return {
users:[]
}
},
methods: {
fetchData(){
axios.get('api/person')
.then(response => (this.users= response.data))
.catch(error => console.log(error));
}
},
}
In ExampleComponent have these lines
<template>
...
<div>{{users.name}}</div>
<div>{{users.ip}}</div>
...
</template>
In api.php
Route::get('/person', function() {
$users = DB::table('user_info')->select('ip','name')->get();
return $users;
});
Running php artisan tinker I did
DB::table('user_info')->select('ip','name')->get();
I've got all my data from DB(users with names and IP's).
In the dev console, I see my data in response tab. But it is nothing in my page.
you need v-for:
<div v-for="user in users">
<div>{{user.name}}</div>
<div>{{user.ip}}</div>
</div>
so for every users you will show info.
There is a problem in vue : it should be {users.ip} and {users.name} in template.
that is how i get my data.
<script>
export default {
data() {
return {
properties: []
}
},
methods: {
loadproperty(){
axios.get('allhouses').then(response => this.properties = response.data);
},
},
mounted() {
this.loadproperty();
}
}
</script>
I am trying to show client information details in the modal. After clicking #click="showDetails(props.row.id)".
I am using axios.get in method and returning the data. Now, It's returning the data as PromiseValue object. How to access PromiseValue to show the value in HTML. Would someone help me please to solve the problem! I am trying like below -
<button #click="showDetails(props.row.id)"><i class="fas fa-eye"></i></button>
And in script-
<script type="text/javascript">
import axios from 'axios';
export default {
data(){
return{
leftPanelVisiblity: false,
singleData: '', }
},
methods:{
showDetails(id){
let b = axios.get('/api/clients/'+id)
.then(function (response) {
return response.data;
}).catch(error => {
alert(error);
});
//console.log(b);
this.singleData = b;
this.leftPanelVisiblity = true
},
}
}
</script>
And finally, I want to access or show the data in the leftPanelVisiblity modal like -
<p>Name: {{ this.singleData.name }}</p>
Or
<p>Name: {{ this.singleData.email }}</p>.
You cannot assign the Axios call to a variable while using Promises (unless you are using await/async).
Instead you should be running the logic within the then callback. Otherwise to the synchronous nature of JavaScript it will run before the request has completed. Your code should look something like this:
methods:{
showDetails(id){
axios.get('/api/clients/'+row.id).then(response => {
//Logic goes here
this.singleData = response.data
this.leftPanelVisibility = true
}).catch(error => {
alert(error);
});
}
}
You need to assign a variable the response of your axios:
showDetails(id){
axios.get('/api/clients/'+id)
.then(function (response) {
this.singleData = response.data;
}).catch(error => {
alert(error);
});
console.log(this.sigleData);
this.leftPanelVisiblity = true
},
I am trying to build an availability carousel. It will show the days of the week, and what time someone is available. I am using Laravel and vue.js. I have done the web api, and I can get the data object following the route
Route::group(['prefix' => '/{area}'], function () {
Route::get('/{tutor}/availability','Tutor\AvailabilityController#show');
});
with this in my availability controller
public function show(Request $request, Area $area, Tutor $tutor)
{
$availability = $tutor->availability()->get();
return response()->json([
'data' => $availability
], 200);
}
That all works.
But when I try and pull it into Vue, nothing shows up. I can't seem to figure out what I might be missing.
I pulled the vue component into blade using the following, and passing in the area and tutor id
<availability area-id="{{ $area->slug }}" tutor-id="{{ $tutor->slug }}">
</availability>
and in Availability.vue, I think where I am going wrong is pulling the data in with props, but I am really not sure anymore.
<script>
$(document).ready(function() {
$("#availability").owlCarousel();
});
export default {
props: {
areaId: null,
tutorId: null
},
data () {
return {
availability: []
}
},
methods: {
getAvailability () {
axios.get( '/' + this.areaId + '/' + this.tutorId + '/availability').then((response) => {
console.log(response.json());
});
}
},
ready () {
this.getAvailability();
}
}
</script>
Thank you for the help.
Axios response object has data field which contains the response from the server. To get the data use
response.data
Also for Vue 2.0 components use mounted instead of ready for when the component is ready. If you are only loading data from the server (and not manipulating the DOM) you can use created instead.
export default {
props: {
areaId: null,
tutorId: null
},
data () {
return {
availability: []
}
},
methods: {
getAvailability () {
var that = this;
axios.get( '/' + this.areaId + '/' + this.tutorId + '/availability')
.then((response) => {
console.log(response.data); // should print {data: availability_object}
// Set this component's availability to response's availability
that.availability = response.data.data;
//OR
//Add response's availability to the components' availability
that.availability.push(response.data.data);
});
}
},
mounted () {
this.getAvailability();
}
}
</script>
I am trying to build a carousel using Laravel 5.6 and Vue.js. I can call the data from db, and console.log response.data. It works like expect it to. Script below.
<script>
$(document).ready(function() {
$("#availability").owlCarousel();
});
export default {
props: {
areaId: null,
tutorId: null,
},
data () {
return {
availability: []
}
},
methods: {
getAvailability () {
var that = this;
axios.get( '/' + this.areaId + '/' + this.tutorId + '/availability').then((response) => {
console.log(response.data)
that.availability = response.data;
});
}
},
mounted () {
this.getAvailability();
}
}
</script>
Now I would expect to be able to display the data like
{{availability.monday_begin}}
but it displays nothing, empty tags.
When I add a second .data to response, so change
that.availability = response.data;
to
that.availability = response.data.data;
The data object shows up as undefined in the vue-dev tools, and {{ availability.monday_begin }} throws an error cannot read property of undefined.
I also tried adding a v-if to the template, based on a couple different articles I read, but nothing I tried worked.
Thanks for your help.
Im trying to get my json result into my react code
The code looks like the following
_getComments() {
const commentList = "AJAX JSON GOES HERE"
return commentList.map((comment) => {
return (
<Comment
author={comment.author}
body={comment.body}
avatarUrl={comment.avatarUrl}
key={comment.id} />);
});
}
How do i fetch AJAX into this?
First, to fetch the data using AJAX, you have a few options:
The Fetch API, which will work out of the box in some browsers (you can use a polyfill to get it working in other browsers as well). See this answer for an example implementation.
A library for data fetching (which generally work in all modern browsers). Facebook recommends the following:
superagent
reqwest
react-ajax
axios
request
Next, you need to use it somewhere in your React component. Where and how you do this will depend on your specific application and component, but generally I think there's two scenarios to consider:
Fetching initial data (e.g. a list of users).
Fetching data in response to some user interaction (e.g. clicking a
button to add more users).
Fetching initial data should be done in the life-cycle method componentDidMount(). From the React Docs:
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
Here they use jQuery to fetch the data. While that works just fine, it's probably not a good idea to use such a big library (in terms of size) to perform such a small task.
Fetching data in response to e.g. an action can be done like this:
var UserGist = React.createClass({
getInitialState: function() {
return {
users: []
};
},
componentWillUnmount: function() {
this.serverRequest && this.serverRequest.abort();
},
fetchNewUser: function () {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
var users = this.state.users
users.push(lastGist.owner.login)
this.setState({ users });
}.bind(this));
},
render: function() {
return (
<div>
{this.state.users.map(user => <div>{user}</div>)}
<button onClick={this.fetchNewUser}>Get new user</button>
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
Lets take a look on the fetch API : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Lets say we want to fetch a simple list into our component.
export default MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
lst: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
fetch('url')
.then((res) => {
return res.json();
})
.then((res) => {
this.setState({ lst: res });
});
}
}
We are fetching the data from the server, and we get the result from the service, we convert is to json, and then we set the result which will be the array in the state.
You can use jQuery.get or jQuery.ajax in componentDidMount:
import React from 'react';
export default React.createClass({
...
componentDidMount() {
$.get('your/url/here').done((loadedData) => {
this.setState({data: loadedData});
});
...
}
First I'd like to use fetchAPI now install of ajax like zepto's ajax,the render of reactjs is asyn,you can init a state in the constructor,then change the state by the data from the result of fetch.