Child component mounts faster than parent - laravel

I use Laravel and Vue. I have two components: parent and child.
Parent:
<template>
<div>
<sport-sites-add :applications-all-list="applicationsAll"></sport-sites-add>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Application id</th>
<th scope="col">Name</th>
<th scope="col">Description</th>
<th scope="col">Picture</th>
<th scope="col">URL</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="sportSite in sportSites">
<th scope="row">{{ sportSite.id }}</th>
<td>
<template v-for="application in sportSite.applications">
id {{ application.id }} => {{ application.name }} <br>
</template>
</td>
<td>{{ sportSite.name }}</td>
<td>{{ sportSite.description }}</td>
<td>
<img style="width: 100px; height: 100px;" :src="sportSite.image" >
</td>
<td>
<a :href="sportSite.url" target="_blank">{{ sportSite.url }}</a>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { EventBus } from '../../app';
export default {
name: "SportSitesTable",
mounted(){
this.loadTable();
this.getApplications();
},
methods:{
loadTable: function () {
window.axios.get('/sport_sites_all')
.then(resp => {
this.sportSites = resp.data.data;
}).catch(err => {
console.error(err);
});
},
getApplications: function () {
window.axios.get('/applications/all')
.then(resp => {
this.applicationsAll = resp.data.applications.data;
}).catch(err => {
console.error(err);
});
}
},
data(){
return {
sportSites: [],
applicationsAll: [],
}
},
}
</script>
Child:
<template>
<div>
<button type="button" class="btn btn-primary my-2" data-toggle="modal" data-target="#sportSiteAdd">
Add
</button>
<div class="modal fade" id="sportSiteAdd" tabindex="-1" role="dialog" aria-labelledby="sportSiteAddLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="sportSiteAddLabel">Add sport site</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul class="alert-danger">
<li v-for="error in errors">
{{ error[0] }}
</li>
</ul>
<form>
<div class="form-group">
<label for="name">Title</label>
<input type="text" class="form-control" id="name" name="name" v-model="formFields.name">
</div>
<div class="form-group">
<label for="image">Picture</label>
<input type="text" class="form-control" id="image" name="image" v-model="formFields.image">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="text" class="form-control" id="url" name="url" v-model="formFields.url">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description" v-model="formFields.description"></textarea>
</div>
<div>
<label class="typo__label">Applications </label>
<multiselect v-model="formFields.applications"
tag-placeholder="Applications"
placeholder="Search"
label="name"
track-by="id"
:options="applications"
:multiple="true"
:taggable="true">
</multiselect>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" v-on:click="submit">Save</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { EventBus } from '../../app';
import Multiselect from 'vue-multiselect'
export default {
name: "SportSitesAdd",
props: ['applicationsAllList'],
methods:{
submit: function (e) {
window.axios.post('/sport_site/add/', this.formFields)
.then(res => {
console.log('Saved!');
$('#sportSiteAdd').modal('hide');
this.formFields.name = '';
this.formFields.image = '';
this.formFields.url = '';
this.formFields.description = '';
EventBus.$emit('reloadApplicationsTable');
}).catch(err => {
if(err.response.status === 422){
this.errors = err.response.data.errors || [];
}
console.error('Error of saving!');
});
},
},
data(){
return {
formFields: {
name: '',
image: '',
url: '',
description: '',
applications: this.applicationsAllList,
},
errors: [],
}
},
components: {
Multiselect
},
}
</script>
The parent component is a table. Child component is a form for the table. I pass a data from the parent to the child via props:
<sport-sites-add :applications-all-list="applicationsAll"></sport-sites-add>
In the child component I have a plugin for creating a multiple select. The plugin requires 'options' and 'values' collections. It's very simple, documentation with my case is here https://vue-multiselect.js.org/#sub-tagging. At the result I want to see the following: all items on the select are selected. But I have just the empty collection during mounting of the child component. I have available items on the 'select' but I dont know how I can make it selected by default. Obviously, I need to copy the applicationsAllList into local data() of child component and use it. But it not available during mounted and beforeMounted.
console.log tells me that the child is faster.

you're missing #tag function & v-model, in this case, must be array, You need to use applicationsAllList props directly on options
<multiselect v-model="formFields.value"
tag-placeholder="Applications"
placeholder="Search"
label="name"
track-by="id"
:options="applicationsAllList"
:multiple="true"
#tag="addTag"
:taggable="true">
</multiselect>
in methods add addTag function and add value as array
data() {
return {
formFields: {
name: '',
value: [],
image: '',
url: '',
description: '',
},
errors: [],
}
},
methods: {
addTag (newTag) {
const tag = {
name: newTag,
code: newTag.substring(0, 2) + Math.floor((Math.random() * 10000000))
}
this.options.push(tag)
this.value.push(tag)
}
}

Related

datatables ajax routes not working on local network

My problem occur in a specific case,
I'm using laravel 7, trying to make small contacts list datatable using ajax CRUD operations .
On localhost every thing is OK but when I deploy it to local network I get (404 not found ajax response)
may controller code:
public function index(Request $request)
{
$cities = State::where("country_id",223 )->get();//223 turkey
$countries = [];
$countries = Country::all(); //select('name')->get()
$datasources = [];
$datasources = DB::table('contacts')->select('data_source')->distinct()->get()->toArray();
$contact_types = [];
$contact_types = DB::table('contacts')->select('contact_type')->distinct()->get()->toArray();
$data = DB::table("contacts")
->leftjoin("countries","contacts.country","=","countries.id")
->leftjoin("states","contacts.city","=","states.id")
->select("contacts.*", "countries.name as countryname", "states.name as statename")
->latest()->get();
if ($request->ajax()) {
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'edit';
$btn = $btn.' delete';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('contacts.contactAjax')->with([ 'contacts'=>$data,
'countries'=> $countries,
'cities'=> $cities,
'datasources'=> $datasources,
'contact_types'=> $contact_types]); //,compact('contacts'));
}
and here may whole view code:
#extends('contacts.layout')
#section('content')
<div class="container">
<h1>Arabist CRM </h1>
<a class="btn btn-success" href="javascript:void(0)" id="createNewContact"> Add contact</a>
<button id="btn-export">EXCEL</button>
{{--onclick="exportTableToExcel('tbl_contacts','conts.xlsx')" <a class="btn btn-success" href="javascript:exportTableToExcel('tbl_contacts','contacts.xlsx')" id="xlsx-export"> excel</a> --}}
<table class="table table-bordered data-table" id="tbl_contacts">
<thead>
<tr>
<th style="padding:10pt 20pt 2pt 2pt; background-image:none;" width="20pt">No</th>
<th style="min-width:75pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="10%">name</th>
<th style="min-width:50pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="10%">company</th>
{{-- <th width="10%">birth</th>
<th>الجنس</th> --}}
<th style="min-width:75pt; padding:10pt 20pt 2pt 2pt; background-image:none;" >email</th>
<th style="min-width:50pt; padding:10pt 20pt 2pt 2pt; background-image:none;">phone</th>
<th style="min-width:120pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="15%">notes</th>
<th style="min-width:40pt; padding:10pt 20pt 2pt 2pt; background-image:none;">contact type</th>
<th style="min-width:40pt; padding:10pt 20pt 2pt 2pt; background-image:none;">city</th>
<th style="min-width:65pt; padding:10pt 20pt 2pt 2pt; background-image:none;">address</th>
<th style="min-width:80pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="8%" style="min-width:100px">control</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="modal fade" id="ajaxModel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
</div>
<div class="modal-body">
<form id="contactForm" name="contactForm" class="form-horizontal">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">company</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="company_name" name="company_name" placeholder="Enter Name" value="" maxlength="50" >
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">email</label>
<div class="col-sm-12">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Name" value="" >
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-2 control-label">phone</label>
<div class="col-sm-12">
<input type="tel" class="form-control" id="phone" name="phone" placeholder="Enter Name" value="" maxlength="50" required="required">
</div>
</div>
<div class="form-group">
<label for="contact_type" class="col-sm-2 control-label">type</label>
<div class="col-sm-12">
<input class="form-control" type="text" list="contact_types" name="contact_type" id="contact_type" placeholder="type" />
<datalist name = "contact_types" id = "contact_types" >
#foreach ($contact_types as $ctp)
<option >{{ $ctp->contact_type }}</option>
#endforeach
</datalist>
</div>
</div>
<div class="form-group" style="display:none;">
<label for="country" class="col-sm-2 control-label" >country</label>
<div class="col-sm-12">
<select class="form-control input-sm" name="country" id="country">
<option value="">--select--</option>
#foreach ($countries as $cnt)
#if($cnt->id == 223 )
<option value="{{ $cnt->id }}" selected>{{$cnt->name}}</option>
#else
<option value="{{ $cnt->id }}">{{$cnt->name}}</option>
#endif
#endforeach
</select>
</div>
</div>
<div class="form-group" style="display:none;">
<label for="city" class="col-sm-2 control-label">city</label>
<div class="col-sm-12">
<select class="form-control input-sm" name="city" id="city">
<option value="">--select--</option>
#foreach ($cities as $cnt)
#if($cnt->id == 3703 )
<option value="{{ $cnt->id }}" selected>{{$cnt->name}}</option>
#else
<option value="{{ $cnt->id }}">{{$cnt->name}}</option>
#endif
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">address</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="address" name="address" placeholder="Enter address" maxlength="50" >
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">notes</label>
<div class="col-sm-12">
<textarea id="notes" name="notes" required="" placeholder="Enter Details" class="form-control"></textarea>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
more details
<button type="submit" class="btn btn-primary" id="saveBtn" value="create">save
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function exportTableToExcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
var table = $('#tbl_contacts').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('ajaxcontacts.index') }}",// "{{ route('ajaxcontacts.index') }}",{{ url('ajaxcontacts.index')}}
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'company_name', name: 'company_name'},
{data: 'email', name: 'email'},
{data: 'phone', name: 'phone'},
{data: 'notes', name: 'notes'},
{data: 'contact_type', name: 'contact_type'},
{data: 'statename', name: 'city'},
{data: 'address', name: 'address'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$('#btn-export').click(function () {
exportTableToExcel("tbl_contacts","fuc.xlsx");
});
$('#createNewContact').click(function () {
$('#saveBtn').val("create-contact");
$('#id').val('');
$('#contactForm').trigger("reset");
$('#modelHeading').html("Create New Contact");
$('#ajaxModel').modal('show');
});
$('body').on('click', '#moreDetails', function () {
var id = $('#id').val();
alert("id: "+ id);
window.location.href = "contacts" +'/' + id +'/edit';//"{{ route('contacts.index') }}"
//$.get("{{ route('contacts.index') }}" +'/' + id +'/edit')
});
$('body').on('click', '.editContact', function () {
var id = $(this).data('id');
//alert("id: "+ id);
$.get( "{{ route('ajaxcontacts.index') }}" + "/" + id +"/edit", function (data) {
//alert("data.name: " + data.name)
$('#modelHeading').html("Edit Contact");
$('#saveBtn').val("edit-user");
$('#ajaxModel').modal('show');
$('#id').val(data.id);
$('#name').val(data.name);
$('#company_name').val(data.company_name);
$('#email').val(data.email);
$('#phone').val(data.phone);
$('#notes').val(data.notes);
$('#contact_type').val(data.contact_type);
$('#data_source').val(data.data_source);
$('#country').val(data.country);
$('#city').val(data.city);
$('#address').val(data.address);
})
});
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#contactForm').serialize(),
url: "{{ route('ajaxcontacts.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#contactForm').trigger("reset");
$('#ajaxModel').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('save changes');
}
});
});
$('body').on('click', '.deleteContact', function () {
var id = $(this).data("id");
confirm("Are You sure want to delete !");
$.ajax({
type: "DELETE",
url: "{{ route('ajaxcontacts.store') }}"+'/'+id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
</body>
#endsection
and web.php routes
Route::resource('ajaxcontacts','ContactAjaxController')->Middleware('isAdmin');
Route::get('ajaxcontacts/index', 'ContactAjaxController#index');
The issue is that you are calling a route from your ajax code, but you have not set up a named route within your web.php route file.
When you use the route() method, Laravel looks for a named route. You call this method several times in your blade file here:
"{{ route('ajaxcontacts.index') }}"
To Fix just name the route in your web.php file:
Route::get('ajaxcontacts/index', 'ContactAjaxController#index')->name('ajaxcontacts.index');

Saving multiple data from dynamic form in Laravel and Vue JS

I have a dynamic form that successfully adds multiple rows by clicking on the add button. the problem is when I try to save data into the database it throws the below error.
{message: "Illegal string offset 'supplier_id'", exception:
"ErrorException",…} exception: "ErrorException" file:
"C:\xampp\htdocs\Bookstore\app\Http\Controllers\API\PurchaseController.php"
line: 87 message: "Illegal string offset 'supplier_id'" trace: [{file:
"C:\xampp\htdocs\Bookstore\app\Http\Controllers\API\PurchaseController.php",
line: 87,…},…]
and help will be highly appreciated
Code in the controller
public function store(Request $request)
{
$products = json_decode($request->getContent('myArray') , true);
foreach( $products as $product )
{
Purchase::create([
'supplier_id' => $product['supplier_id'],
'date' => $product['date'],
'totalAmount' => $product['totalAmount'],
'description' => $product['description']
]);
}
// return dd($myArray);
return response()->json($Purchase);
}
Form in the Purchases Vue
<form
#submit.prevent="
editMode ? updatePurchase() : createPurchase()
"
>
<div class="modal-body">
<div class="form-horizontal">
<tr v-for="(invoice_product, k) in invoice_products" :key="k">
<td scope="row" class="trashIconContainer">
<i class="fa fa-trash" #click="deleteRow(k, invoice_product)"></i>
</td>
<td style="width: 20%;">
<select
name="supplier_id[]"
id="supplier_id"
:class="{
'is-invalid': form.errors.has(
'supplier_id'
)
}"
class="form-control"
v-model="invoice_product.supplier_id"
data-live-search="true"
>
<option value selected>د پلورونکي ټاکنه</option>
<option
v-for="Supplier in Suppliers"
:key="Supplier.id"
:value="Supplier.id"
>{{ Supplier.name }}</option>
</select>
<has-error :form="form" field="supplier_id"></has-error>
</td>
<td style="width: 20%;padding-right: 10px;">
<input
dir="rtl"
id="text1"
v-model="invoice_product.date"
placeholder="نیټه "
type="date"
name="date[]"
class="form-control"
:class="{
'is-invalid': form.errors.has('date')
}"
/>
<has-error :form="form" field="date"></has-error>
</td>
<td style="width: 20%;padding-right: 10px;">
<input
dir="rtl"
id="text1"
v-model="invoice_product.totalAmount"
placeholder=" ټولی پیسی "
type="number"
name="totalAmount[]"
class="form-control"
:class="{
'is-invalid': form.errors.has(
'totalAmount'
)
}"
/>
<has-error :form="form" field="totalAmount"></has-error>
</td>
<td style="width: 40%;padding-right: 10px;">
<textarea
v-model="invoice_product.description"
placeholder="تشریح"
type="text"
name="description[]"
class="form-control"
:class="{
'is-invalid': form.errors.has(
'description'
)
}"
></textarea>
<has-error :form="form" field="description"></has-error>
</td>
</tr>
<button type="button" class="btn btn-info" #click="addNewRow">
<i class="fa fa-plus-circle"></i>
Add
</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">لغوه کړی</button>
<button
v-show="editMode"
:disabled="form.busy"
type="submit"
class="btn btn-success"
>تازه کړی</button>
<button
v-show="!editMode"
:disabled="form.busy"
type="submit"
class="btn btn-primary"
>خوندی کړی</button>
</div>
</div>
</form>
Sript in the Purchases Vue
data() {
return {
invoice_products: [
{
supplier_id: "",
totalAmount: "",
date: "",
description: ""
}
],
}
deleteRow(index, invoice_product) {
var idx = this.invoice_products.indexOf(invoice_product);
console.log(idx, index);
if (idx > -1) {
this.invoice_products.splice(idx, 1);
}
this.calculateTotal();
},
addNewRow() {
this.invoice_products.push({
supplier_id1: "",
totalAmount1: "",
date1: "",
description1: ""
});
},
createPurchase() {
axios
.post("api/Purchase", {
myArray: this.invoice_products
})
.then(() => {
$("#addNew").modal("hide");
toast.fire({
icon: "success",
html: "<h5> معلومات په بریالیتوب سره خوندي شول</h5>"
});
Fire.$emit("refreshPage");
this.form.reset();
})
.catch(er => {
console.log(er);
});
},
I found the solution
public function store(Request $request)
{
if ($purchases= $request->get('myArray')) {
foreach($purchases as $purchase) {
Purchase::create([
'supplier_id' => $purchase['supplier_id'],
'date' => $purchase['date'],
'totalAmount' => $purchase['totalAmount'],
'description' => $purchase['description']
]);
}
}
return response()->json();
}

i try to mount a component in a component vue

i i try to mount a component in a component, this component its a partial, in especifict its a paginator, which i need to integrate, i use props in the paginate component.
but i have a problem, in the console appears the next messagge "Failed to mount component: template or render function not defined." i am new in vue js, i using router-view i don´t know if this
it is affecting en the problem the code its the next :
Pedido.vue
<template>
<div id="pedido" style="margin-top:50px">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Pedidos</h4>
<div class="card-tools" style="position: absolute;right: 1rem;top: .5rem;">
<button type="button" class="btn btn-info" >
Nuevo
<i class="fas fa-plus"></i>
</button>
<button type="button" class="btn btn-primary" >
Recargar
<i class="fas fa-sync"></i>
</button>
</div>
</div>
<div class="card-body">
<div class="mb-3">
<div class="row">
<div class="col-md-2">
<strong>Buscar por :</strong>
</div>
<div class="col-md-3">
<select class="form-control" id="fileds">
<option value="total">Codigo</option>
<option value="name">Nombre</option>
<option value="email">Apellido</option>
<option value="phone">Telefono</option>
<option value="address">Direccion</option>
</select>
</div>
<div class="col-md-7">
<input type="text" class="form-control" placeholder="Buscar">
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th scope="col">Codigo</th>
<th scope="col">Nombre</th>
<th scope="col">Apellido</th>
<th scope="col">Telefono</th>
<th scope="col">Rut</th>
<th scope="col" class="text-center">Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(pedido, index) in pedidos" :key="pedido.codigo">
<th scope="row">{{ index + 1}}</th>
<td>{{ pedido.nombre_cliente}}</td>
<td>{{ pedido.apellido_cliente }}</td>
<td>{{ pedido.telefono_cliente}}</td>
<td>{{ pedido.rut_cliente }}</td>
<td class="text-center">
<button type="button" class="btn btn-info btn-sm">
<i class="fas fa-eye"></i>
</button>
<button type="button" class="btn btn-primary btn-sm">
<i class="fas fa-edit"></i>
</button>
<button
type="button"
class="btn btn-danger btn-sm"
>
<i class="fas fa-trash-alt"></i>
</button>
</td>
</tr>
<tr >
<td colspan="6">
<div class="alert alert-danger" role="alert">No se ah encontrado resultados :(</div>
</td>
</tr>
</tbody>
</table>
<div class="card-footer">
<pagination
v-if="pagination.last_page > 1"
:pagination="pagination"
:offset="5"
#paginate="getData()"
></pagination>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
pedidos:[],
pagination: {
current_page: 1,
},
}
},
mounted() {
console.log('Component mounted.')
this.getData();
},
methods:{
getData(){
this.$Progress.start();
axios.get("api/pedidos?page=" + this.pagination.current_page)
.then(response =>{
this.pedidos = response.data.data;
this.pagination = response.data.meta;
this.$Progress.finish();
})
.catch(e =>{
console.log(e)
this.$Progress.fail();
})
//.then(({ data }) => (this.pedidos = data));
}
},
}
</script>
this its PaginationComponent.vue:
<template>
<nav aria-label="...">
<ul class="pagination justify-content-center">
<li class="page-item" :class="{ disabled: pagination.current_page <= 1 }">
<a class="page-link" #click.prevent="changePage(1)" >First page</a>
</li>
<li class="page-item" :class="{ disabled: pagination.current_page <= 1 }">
<a class="page-link" #click.prevent="changePage(pagination.current_page - 1)">Previous</a>
</li>
<li class="page-item" v-for="page in pages" :key="page" :class="isCurrentPage(page) ? 'active' : ''">
<a class="page-link" #click.prevent="changePage(page)">{{ page }}
<span v-if="isCurrentPage(page)" class="sr-only">(current)</span>
</a>
</li>
<li class="page-item" :class="{ disabled: pagination.current_page >= pagination.last_page }">
<a class="page-link" #click.prevent="changePage(pagination.current_page + 1)">Next</a>
</li>
<li class="page-item" :class="{ disabled: pagination.current_page >= pagination.last_page }">
<a class="page-link" #click.prevent="changePage(pagination.last_page)">Last page</a>
</li>
</ul>
</nav>
</template>
<script>
export default {
props:['pagination', 'offset'],
methods: {
isCurrentPage(page){
return this.pagination.current_page === page
},
changePage(page) {
if (page > this.pagination.last_page) {
page = this.pagination.last_page;
}
this.pagination.current_page = page;
this.$emit('paginate');
}
},
computed: {
pages() {
let pages = []
let from = this.pagination.current_page - Math.floor(this.offset / 2)
if (from < 1) {
from = 1
}
let to = from + this.offset -1
if (to > this.pagination.last_page) {
to = this.pagination.last_page
}
while (from <= to) {
pages.push(from)
from++
}
return pages
}
}
}
</script>
app.js
Vue.component('pagination', require('./components/partial/PaginationComponent.vue'));
const app = new Vue({
el: '#app',
router
});
this its the error
but in the extension of vue in the console i see the
properties of the object, this is fine,
but I do not know what I'm doing wrong, like I said I'm new to this.
extension of vue
I hope they understand me,
I would greatly appreciate your help.
Pedido.vue
export default {
components: { pagination },
data(){ ....
maybe is this problem
On the file app.js you apart from especify where you are mounting your component (in this case on the div with id "app"), you also need to tell Vue what to render.
Your component on the app.js file should include a template or a render function, that's why you are getting the error "Failed to mount component: template or render function not defined.
You can add it like this:
const app = new Vue({
el: '#app',
router,
template: '<pagination/>'
});
Or using the render function like this:
import Pagination from './components/partial/PaginationComponent.vue'
const app = new Vue({
el: '#app',
router,
render: (h) => h(Pagination)
});
well, i tried with their answer, but dont worked ,
I managed to solve it by adding:
Vue.component('pagination', require('./components/partial/PaginationComponent.vue').default);

Fetch Records in Angular datatable

Im new to Angular and My Requirement is
A component includes a form with the field name call "Brand" and a button to add the same record to database through angular service and there should be a datatable which is fetching all brand data from database to data table.
so by using fetchall method in ts file, i am assigning values to data table. im calling fetchall method to ngoninit() which helps me to show the data in table while component get initialized. to add record, i am using a method call addyear() and calling the same method to onSumbit(). my problem is when i add the record to database, i should be able to load newly added record to angular data table! since that method in ngoninit(), i have to refresh the browser to get the record in data table kindly give me a solution. for the back end, im using Spring boot with Postgres database
My Component TS file
constructor(private brandService:BrandService,private toastyService: ToastyService) { }
ngOnInit() {
this.findbrand();
}
onSubmit()
{
this.saveBrand();
this.submitted=true;
}
saveBrand()
{
this.brandService.addbrand(this.brand).subscribe
(data=>this.addToast({title:'Record Has been added Successfully', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'success'}),
error=>this.addToast({title:'Record Not Added! Sorry', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'error'}));
this.brand=new Brand();
}
findbrand()
{
this.brandService.findbrand().subscribe(data=>this.data=data,error=>this.addToast({title:'Record Cannot be found! Sorry', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'error'}));
}
My Service.TS file
export class BrandService {
constructor(private http:HttpClient) { }
private baseUrl='http://localhost:8080/snazzy-engine/brand';
addbrand(brand:object):Observable<any>
{
return this.http.post(`${this.baseUrl}` + `/insert`, brand,{
headers: {'schemaName':'test.'}
});
}
findbrand():Observable<any>
{
return this.http.get(`${this.baseUrl}` + `/find-all`,{
headers: {'schemaName':'test.'}
});
}
getbrandid(id: number): Observable<Object> {
return this.http.get(`${this.baseUrl}/find-one/${id}`, {headers:
{'schemaName':'test.'}});
}
}
My HTML File
<div class="table-content crm-table">
<div class="project-table">
<div id="crm-contact" class="dt-responsive">
<div class="row">
<div class="col-xs-12 col-sm-12 col-sm-12 col-md-6">
<div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-6">
<div style="text-align: right;">
<label>Search:
<input type="search" [(ngModel)]="filterQuery" class="form-control input-sm full-data-search" placeholder="Search name">
</label>
</div>
</div>
</div>
<!-- <div class="panel-heading">User information</div>-->
<div class="table-responsive">
<table class="table table-bordered table-hover table-sm" [mfData]="data | dataFilter : filterQuery" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage" [(mfSortBy)]="sortBy"
[(mfSortOrder)]="sortOrder">
<thead class="thead-dark text-center">
<tr>
<th style="width:10%">
<mfDefaultSorter by="brandId">Brand ID</mfDefaultSorter>
</th>
<th style="width:70%">
<mfDefaultSorter by="name">Brand Name</mfDefaultSorter>
</th>
<th style="width:10%">
<mfDefaultSorter by="more">More</mfDefaultSorter>
</th>
<th style="width:10%">
<mfDefaultSorter by="checkbox">Delete</mfDefaultSorter>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of mf.data; let i = index;">
<td>{{item.brandId}}</td>
<td>{{item.brand}}</td>
<td class="action-icon">
<button type="button" class="btn btn-sm btn-primary" (click)="findybrandid(item.brandId);modalDefault.show();">
edit
</button>
</td>
<td>
<div class="checkbox text-center">
<label><input type="checkbox" value=""></label>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="10">
<mfBootstrapPaginator class="pagination-main f-right"></mfBootstrapPaginator>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div style="text-align:center;">
<button class="btn btn-out btn-danger ripple light"><i class="icofont icofont-check-circled"></i>Delete</button>
</div>
</div>
</div>
</div>
try this
saveBrand()
{
this.brandService.addbrand(this.brand)
.subscribe(
data => this.addToast(
{
title:'Record Has been added Successfully',
msg:'',
timeout: 5000,
theme:'default',
position:'top-right',
type:'success'
}),
error => this.addToast(
{
title:'Record Not Added! Sorry',
msg:'',
timeout: 5000,
theme:'default',
position:'top-right',
type:'error'
})
);
this.data.push(this.brand); /*change: push new data into an array*/
this.brand=new Brand();
}

Info not displaying in modal, however no errors and Vue component works in console

Looking to display data in a modal. My set up is as follows:
app.js
Vue.component('modal', require('./components/Modal.vue'));
const app = new Vue({
el: '#vue',
data() {
return {
id: '',
booking_start: '',
booking_end: '',
car: [],
user: []
};
},
});
Modal.vue component:
<template>
<div id="modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<slot name="header"></slot>
</div>
<div class="modal-body">
<slot></slot>
</div>
<div class="modal-footer">
<slot name="footer"></slot>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</template>
<script>
export default {
name: 'modal',
mounted() {
console.log('Modal mounted.')
},
data() {
return {}
},
props: ['id', 'booking_start', 'car', 'user'],
mounted() {
}
}
</script>
Laravel blade:
<div id="vue">
<modal v-bind="{{json_encode($reservation)}}">
<template slot="header">
<strong>Vehicle Checkout</strong>
</template>
<p>Ready to check out this vehicle?</p>
<table class="table table-sm">
<tr>
<th>Vehicle Name</th>
<td><span id="reservation-car-name">#{{ car.name }}</span></td>
</tr>
<tr>
<th>Vehicle Make / Model</th>
<td><span id="reservation-car-make-model"></span></td>
</tr>
<tr>
<th>Vehicle Registration</th>
<td><span id="reservation-car-registration"></span></td>
</tr>
<tr>
<th>Odometer Start</th>
<td><span id="reservation-car-odometer"></span></td>
</tr>
</table>
<template slot="footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Checkout</button>
</template>
</modal>
</div>
At this point, I am just attempting to get the data to show in the modal.
Looking at the Vue Dev tools:
There are no errors in the console, and I can output the data I am after in the console.
I'm probably missing something very basic as I am new to Vue, but I can't for the life of me work out what it is.
Component tag replaced by template content, so put all content into modal component from component tag <modal>.your content.</modal>
Vue.component('modal',{
props:['car'],
template: `<div><template slot="header">
<strong>Vehicle Checkout</strong>
</template>
<p>Ready to check out this vehicle?</p>
<table class="table table-sm">
<tr>
<th>Vehicle Name</th>
<td><span id="reservation-car-name">{{ car.name }}</span></td>
</tr>
<tr>
<th>Vehicle Make / Model</th>
<td><span id="reservation-car-make-model">{{ car.model }}</span></td>
</tr>
<tr>
<th>Vehicle Registration</th>
<td><span id="reservation-car-registration">{{ car.reg }}</span></td>
</tr>
<tr>
<th>Odometer Start</th>
<td><span id="reservation-car-odometer">{{ car.odo }}</span></td>
</tr>
</table>
<template slot="footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Checkout</button>
</template>
</div>`
})
const app = new Vue({
el: '#vue',
data() {
return {
id: '',
booking_start: '',
booking_end: '',
car: {name:'test1',model:'gh201',reg:'201821542',odo:'2018-01-01'},
user: []
};
},
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="vue">
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<modal :car="car"></modal>
</div>
</div>
</div>
</div>
My other answers related this issue : router view and transition-group

Resources