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

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

Related

DataTables warning: table id=category_table - Invalid JSON response. datatable ajax laravel

i am using delete method to destroy an item of the category table but when i reload the datatable function ajax it gives me an error DataTables warning: table id=category_table - Invalid JSON response. i don't know why it returns this error please help i want to refresh the table without refreshing the website
note:the delete method works fine
my table
<h1>all categories</h1>
<table class="table" id="category_table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">name</th>
<th scope="col">edit</th>
<th scope="col">delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
my ajax code
<script>
$(document).ready(function(){
$('body').on('click','#delete',function(){
var id = $(this).val();
$('#deleteexampleModal').modal('show');
$("#deleteid").val(id);
});
});
$('#deleteform').submit(function(e){
e.preventDefault();
var id = $("#deleteid").val();
// console.log(id);
$.ajax({
url: 'categories/'+id,
type: "DELETE",
dataType: 'json',
success:function(response){
console.log(response);
$("#deleteexampleModal").modal('hide');
// window.location.reload();
$('#category_table').DataTable().ajax.reload();
}
});
});
and my modal when clicking the delete button
<!-- delete Modal -->
<div class="modal fade" id="deleteexampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add new Product</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" id="deleteform" name="form">
#csrf
#method('DELETE')
<div class="form-group">
are you sure you want to delte this item?
<input type="text" id="deleteid" name="deleteid">
</div>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
my delete method
public function deleteCategory($id){
$category = Category::find($id)->delete();
return response()->json([
'status' => 200,
'message' => 'deleted succfully'
]);
}

Vue component doesn't load

I want to load a vue component after I click on the "next" button. The project is laravel + vue.
The components load if I put them direct into laravel blade(you can see them below) but if I try to open component from the component it does'nt work. I don't get eny error it just stays the same component. The route in the address bar changes to the route that it should change... I mean it's really starnge.
app.js:
require('./bootstrap');
window.Vue = require('vue').default;
import Vue from 'vue';
import VueRouter from 'vue-router';
import { routes } from './routes';
Vue.use(VueRouter);
Vue.component('productinfo-index', require('./components/productInfo/index.vue').default);
Vue.component('audit-index', require('./components/audit/index.vue').default);
Vue.component('audit-info', require('./components/audit/auditInfo.vue').default);
const router = new VueRouter({
mode: 'history',
routes: routes
});
const app = new Vue({
el: '#app',
router: router
});
Routes.js:
import ProductInfoIndex from './components/productInfo/index';
import Audit from './components/audit/index';
import AuditInfo from './components/audit/auditInfo';
export const routes = [
{
path: '/productInfo',
name: 'ProductInfoIndex',
component: ProductInfoIndex
},
{
path: '/audit',
name: 'Audit',
component: Audit
},
{
path: '/audit/info',
name: 'AuditInfo',
component: AuditInfo
}
];
Index.vue:
<template>
<div>
<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">Inventorizacija</h1>
</div>
<div class="row">
<div class="card mx-auto">
<div class="card-header">
<router-link
:to="{name: 'AuditInfo'}"
class="btn btn-primary mb-2"
>Next</router-link>
</div>
<!-- <div v-if="showMessage">
<div class="alert alert-success">{{ message }}</div>
</div> -->
<div class="card-body">
<table class="table">
<thead>
<tr>
<th scope="col">Pavadinimas</th>
<th scope="col">Pradėta</th>
</tr>
</thead>
</div>
</div>
</div>
</div>
</template>
AuditInfo.vue(the component that should be loaded):
<template>
<div class="row">
<div class="card mx-auto">
<div class="card-header">
<router-link
:to="{name: 'Audit'}"
class="btn btn-primary mb-2"
>Back</router-link>
</div>
<div class="card-body">
<table class="table">
<thead>
<tr>
<th scope="col">Pavadinimas</th>
<th scope="col">Pradėta</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
You should put <router-view /> somewhere in the index.vue for rendering router component.

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);

I want to set local-storage and qty increment in every click when product ID already exist in cart by Vue.js

I made a shopping cart, where a product item gets added to the cart. When I click the product, it gets stored in a cart, but not local storage. I set it local-storage. When I click a product that already exists in the cart, I want to increment its quantity, but that's not happening. It adds another row instead, which I want to prevent.
Here is my component:
<template>
<div class="row">
<div class="col-md-8">
<div v-for="(product, id) in products" :key="id" class="col-xl-3 col-sm-6 mb-3 float-left">
<div class="card o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class="fas fa-fw fa-comments"></i>
</div>
<div class="mr-5">{{product.name}}</div>
</div>
<div class="card-footer clearfix small z-1 form-group row" href="#">
<span class="float-left"><input type="text" v-model="product.qty" class="form-control form-control-sm mb-2"></span>
<strong class="float-right col-sm-6">
{{product.price}} TK
</strong>
<button class="btn btn-sm btn-info float-right col-sm-6" #click="addToCart(product)">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<table class="table table-sm">
<thead>
<tr>
<th>#SL</th>
<th>Name</th>
<th>Qty</th>
<th>Price</th>
<th>L/T</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(cart, i) in carts" :key="i">
<td>{{cart.id}}</td>
<td>{{cart.name}} </td>
<td class="text-right">{{cart.qty}}</td>
<td class="text-right">{{cart.price}}</td>
<td class="text-right">{{cart.price*cart.qty}}</td>
<td><button type="button" #click="removeProduct(i)" class="btn btn-sm btn-danger">x</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4" class="text-right font-weight-bold">Total</td>
<td class="text-right"> {{total}}/-</td>
</tr>
</tfoot>
</table>
<div>
<button class="btn btn-sm btn-info float-right">Checkout</button>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
products:[],
carts:[],
}
},
computed:{
total(){
var total = 0
this.carts.forEach(cart => {
total += parseFloat(cart.price * cart.qty)
})
return total
},
},
mounted(){
this.showProduct()
},
methods:{
showProduct(){
axios.get('api/pos')
.then(res=>{
this.products = res.data.data
});
},
addToCart(product){
this.carts.push(product)
},
removeProduct(i){
this.carts.splice(i,1)
}
}
}
</script>
Here is the screenshot:
The problem is addToCart() just pushes another product into the cart without checking if it already exists.
To fix the problem, update that method to find the item, and increment the item's quantity if found. Otherwise, push another item into the cart:
addToCart(product) {
if (this.carts.find(p => p.id === product.id)) {
product.qty++
} else {
this.carts.push(product)
}
}

Child component mounts faster than parent

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)
}
}

Resources