nuxt,js vue,js how to fetch data inside of table - laravel

i am new in vuetify and nuxt.js
i am getting data from database but i want to show that in vuetify table.
Laravel API Controller
public function businesslist() {
$businesslist = Business::paginate(2)->toJson(JSON_PRETTY_PRINT);
return response($businesslist);
}
}
MY Laravel API
Route::get('/businesslist', 'BusinessController#userlist')->name('businesslist');
MY Nuxt.js vue page
<template>
<v-card>
<v-card-title>
Nutrition
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
></v-text-field>
</v-card-title>
<v-data-table
:headers="headers"
:items="businessuser"
:search="search"
></v-data-table>
</v-card>
</template>
<script>
export default {
data() {
return {
search: '',
headers: [{
text: 'Name',
value: 'name'
},
{
text: 'Mobile ',
value: 'mobile_number'
},
{
text: 'Location ',
value: 'location'
},
{
text: 'Join Date ',
value: 'registration_date'
},
{
text: 'Renewal Date ',
value: 'registration_renewal_date'
},
],
businessuser: [
],
}
},async asyncData({$axios}) { let {data} = await $axios.$get('/businesslist')
return {
businesslist: data
} },
}
}
</script>

You should use created event, in this event, call your businesslist API and in the response, you should assign received data to your businessuser vue js variable.
Let see here one example.
created () {
this.initialize();
},
methods: {
initialize () {
this.businessuser = businesslistApiCalling();
}
}
businesslistApiCalling(); is just an example you should call here the API method to receive Json data from the Server.

Related

How to display records from Laravel via Vuetify v-data-table component

I have a project build in Laravel with Vue.js which work perfect statically, but I need convert it into dynamically to pull records from database table to v-data-table component.
I know Laravel and I know How these things works via Ajax/jQuery but I'm pretty new in Vue.js
Can someone explain to me how to display the results from the database in the v-data-table component.
Thanks.
Here is the Vue.js file:
<template>
<v-app>
<v-main>
<div>
<v-tab-item>
<v-card flat>
<v-card-text>
<v-card-title>
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
></v-text-field>
</v-card-title>
<v-data-table
:headers="headers"
:items="items"
:items-per-page="5"
class=""
:search="search">
</v-data-table>
</v-card-text>
</v-card>
</v-tab-item>
</div>
</v-main>
</v-app>
</template>
<script>
export default {
data: () => ({
search: '',
items: [],
headers: [
{
text: '#',
align: 'start',
sortable: false,
value: 'id',
},
{ text: 'Name', value: 'name' },
{ text: 'Slug', value: 'slug' },
],
/*THIS IS A STATIC DATA*/
// items: [
// {
// id: 1,
// name: 'Test Name 1',
// slug: 'test-name-1',
// },
// {
// id: 2,
// name: 'Test Name 2',
// slug: 'test-name-2',
// },
// ],
/*THIS IS A STATIC DATA*/
}),
created () {
this.getItems();
},
methods: {
getItems() {
axios
.get('/test/vue')
.then((response) => {
this.items = response.data,
console.log(response.data)
})
.catch(error => console.log(error))
},
}
}
</script>
And Here is Blade file:
#extends('it-pages.layout.vuetify')
#section('content')
<div id="appContainer">
<software-template></software-template>
</div>
Output in the console is :
console.log
Response from axios is also Ok
response
My Controller :
public function showData()
{
$items = Category::select('id', 'name', 'slug')->where('order', 1)->get();
// dd($items);
return response()->json(['items' => $items]);
}
My route:
Route::get('test/vue', 'PagesController#showData');
console.log after changes axios lines
console-log
So there were multiple issues here:
The backend did you return a correct array
The frontend performed a post request instead of a get
The this context is not correct since you are using a function instead of arrow syntax
Make sure to look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions and read about how this changes how this is elevated.
In your case, you need to change the code on the then part of your axios call:
.then((response) => {
this.items = response.data
})
I must to say that I solve the problem.
Problem was been in axios response.
Instead this.items = response.data I change to this.items = response.data.items and it work perfectly.
methods: {
getItems() {
axios
.get('/test/vue')
.then((response) => {
this.items = response.data.items
console.log(response.data.items)
})
.catch(error => console.log(error))
},
}

How to append the axios result to vuejs datatables?

I am new to vuejs. I have a laravel+vue project in which I had used vuejs datatables for displaying all the users. I am stuck on why the data is not appending to the datatable :data property and I also tried to display data in <div v-for="user in users">{{ user.name }}</div> tag with for loop then it is displaying but when I used for loop in datatable then loop doesn't stops and also there is no error in the console. Please tell me the solution and thanks in advance. Here is my code.
UserController.php
public function index()
{
return response()->json(['users' => User::all()], 200);
}
UserComponent.vue
<template>
<datatable :columns="columns" :data="users"></datatable>
</template>
<script>
export default()
{
data()
{
return {
columns: [
{label: 'id', field: 'id'},
{label: 'Name', field: 'name'},
{label: 'Email', field: 'email'}
],
users: []
};
},
mounted()
{
this.getUsers();
},
methods:
{
getUsers()
{
axios.get('api/user')
.then(res => this.users = res.data.users)
.catch(err => console.log(err))
},
}
}
</script>

Auto fill input field after Select dropdown list [ Laravel, Vuejs ]

I want to create something that search in Product table and i select in dropdown its will display data in order table like pic below?
how can i archieve that? Anyone give me any hint?
thanks in advances...
In my Vuetify
i used vue-select package
<v-col md="6" cols="12">
<label class="font-weight-bold">Select Product</label>
<v-select v-model="search" label="name" :options="purchases"></v-select>
</v-col>
In my script file
<script>
export default {
created() {
this.fetchData()
},
data() {
return {
form: {},
search: '',
items: [],
purchase_status: ['Received', 'Partial', 'Pending', 'Ordered'],
}
},
methods: {
fetchData() {
this.$axios.$get(`api/product`)
.then(res => {
this.items = res.data;
console.log(this.items)
})
.catch(err => {
console.log(err)
})
},
uploadFile(event) {
const url = 'http://127.0.0.1:3000/product/add_adjustment';
let data = new FormData();
data.append('file', event.target.files[0]);
let config = {
header: {
'content-Type' : 'image/*, application/pdf'
}
}
this.$axios.$post(url,data,config)
.then(res => {
console.log(res);
})
}
}
}
</script>
When you select a product in the dropdown, you'll get product_id. Use this product_id and call API to get data for the orders table.

Binding a v-data-table to a props property in a template

I have a vue component which calls a load method returning a multi-part json object. The template of this vue is made up of several sub-vue components where I assign :data="some_object".
This works in all templates except for the one with a v-data-table in that the v-for process (or the building/rendering of the v-data-table) seems to kick-in before the "data" property is loaded.
With an npm dev server if I make a subtle change to the project which triggers a refresh the data-table then loads the data as I expect.
Tried various events to try and assign a local property to the one passed in via "props[]". Interestingly if I do a dummy v-for to iterate through or simply access the data[...] property the subsequent v-data-table loads. But I need to bind in other rules based on columns in the same row and that doesn't work.
Parent/main vue component:
...
<v-flex xs6 class="my-2">
<ShipViaForm :data="freight"></ShipViaForm>
</v-flex>
<OrderHeaderForm :data="orderheader"></OrderHeaderForm>
<v-flex xs12>
<DetailsForm :data="orderdet" :onSubmit="submit"></DetailsForm>
</v-flex>
...
So in the above the :data property is assigned from the result below for each sub component.
...
methods: {
load(id) {
API.getPickingDetails(id).then((result) => {
this.picking = result.picking;
this.freight = this.picking.freight;
this.orderheader = this.picking.orderheader;
this.orderdet = this.picking.orderdet;
});
},
...
DetailsForm.vue
<template lang="html">
<v-card>
<v-card-title>
<!-- the next div is a dummy one to force the 'data' property to load before v-data-table -->
<div v-show="false">
<div class="hide" v-for='header in headers' v-bind:key='header.product_code'>
{{ data[0][header.value] }}
</div>
</div>
<v-data-table
:headers='headers'
:items='data'
disable-initial-sort
hide-actions
>
<template slot='items' slot-scope='props'>
<td v-for='header in headers' v-bind:key='header.product_code'>
<v-text-field v-if="header.input"
label=""
v-bind:type="header.type"
v-bind:max="props.item[header.max]"
v-model="props.item[header.value]">
</v-text-field>
<span v-else>{{ props.item[header.value] }}</span>
</td>
</template>
</v-data-table>
</v-card-title>
</v-card>
</template>
<script>
import API from '#/lib/API';
export default {
props: ['data'],
data() {
return {
valid: false,
order_id: '',
headers: [
{ text: 'Order Qty', value: 'ord_qty', input: false },
{ text: 'B/O Qty', value: 'bo_qty', input: false },
{ text: 'EDP Code', value: 'product_code', input: false },
{ text: 'Description', value: 'product_desc', input: false },
{ text: 'Location', value: 'location', input: false },
{ text: 'Pick Qty', value: 'pick_qty', input: true, type: 'number', max: ['ord_qty'] },
{ text: 'UM', value: 'unit_measure', input: false },
{ text: 'Net Price', value: 'net_price', input: false },
],
};
},
mounted() {
const { id } = this.$route.params;
this.order_id = id;
},
methods: {
submit() {
if (this.valid) {
API.updateOrder(this.order_id, this.data).then((result) => {
console.log(result);
this.$router.push({
name: 'Orders',
});
});
}
},
clear() {
this.$refs.form.reset();
},
},
};
</script>
Hopefully this will help someone else who can't see the forest for the trees...
When I declared the data() { ... } properties in the parent form I initialised orderdet as {} instead of [].

vue-multiselect with both tagging and async, stops working

I'm using vue-multiselect and I would like the user to be able to search tags in the database using async and if they don't find what they want, enter their own tag. This means I'm using tagging and async. It works as expected until I add a tag not found in the , then the aysnc no longer searches. If I remove the added tag, then it does the async search again..
<template>
<div>
<label class="typo__label" for="ajax">Async multiselect</label>
<multiselect v-model="selectedTags" id="tags" label="name" track-by="code" placeholder="Type to search" open-direction="bottom" :options="tags" :taggable="true" #tag="addTag" :multiple="true" :searchable="true" :loading="isLoading" :internal-search="false" :clear-on-select="true" :close-on-select="false" :options-limit="300" :limit="3" :limit-text="limitText" :max-height="600" :show-no-results="false" :hide-selected="true" #search-change="asyncFind">
<template slot="clear" slot-scope="props">
<div class="multiselect__clear" v-if="selectedTags.length" #mousedown.prevent.stop="clearAll(props.search)"></div>
</template><span slot="noResult">Oops! No elements found. Consider changing the search query.</span>
</multiselect>
<pre class="language-json"><code>{{ selectedTags }}</code></pre>
</div>
</template>
<script>
import axios from 'axios';
import Multiselect from 'vue-multiselect'
export default {
components: {
Multiselect
},
props: {
userId: {
type: Number,
required: true
},
tagGroup: {
type: String,
required: true
}
},
data () {
return {
selectedTags: [],
tags: [],
isLoading: false
}
},
methods: {
addTag (newTag) {
const tag = {
name: newTag
}
this.tags.push(tag)
this.selectedTags.push(tag)
},
limitText (count) {
return `and ${count} other tags`
},
asyncFind (query) {
if( query.length > 3 ) {
this.isLoading = true
axios.get('/api/tags/'+this.tagGroup+'/'+query).then(response => {
this.tags = response.data.results.map(a => {
return { name: a.name.en };
});
})
}
},
clearAll () {
this.selectedTags = []
}
}
}
</script>
I'm using the component twice within another component:
<user-tags v-bind:tagGroup="'industry'" :typeahead-activation-threshold="2" :userId="user.id" :isSearchable="true"></user-tags>
<user-tags v-bind:tagGroup="'expertise'" :typeahead-activation-threshold="2" :userId="user.id" :isSearchable="true"></user-tags>

Resources