Компонент Livewire не вызывает методы javascript

#javascript #laravel #events #laravel-livewire

Вопрос:

У меня есть компонент livewire, который отправляет некоторые события браузера для чтения в файле js, который содержит прослушиватели и охватывает приятные оповещения о каждом событии. проблема в том, что, когда я изменил свой компонент livewire для вызова другой функции, функция выполняется. Однако события диспетчерских браузеров не работают. вот код:

Файл JS

 $(function () {
    "use strict";

    window.addEventListener("comprobante-cargado", function (data) {
        $("#modal_cargar_comprobante").modal("hide");

        Swal.fire(data.detail)
        .then((result) => {
            if(result.isConfirmed){

                window.livewire.emit('redireccion-inicio');

            }
        });
        $().alert('dispose')
        
    });

    window.addEventListener("factura-enviada", function (data) {
        $("#modal_generar_factura").modal("hide");

        Swal.fire(data.detail)
        .then((result) => {
            if(result.isConfirmed){

                window.livewire.emit('redireccion-inicio');

            }
        });
        
    });
    
    window.addEventListener("factura-reenviada", function (data) {

        Swal.fire(data.detail)
        .then((result) => {
            if(result.isConfirmed){

                window.livewire.emit('redireccion-inicio');

            }
        });
        
    });

    window.addEventListener("swal:error", function (data) {

        Swal.fire(data.detail);
        
    });
    
});
 

Функция компонента Livewire

 public function reenviarFactura(){

        $facturador = new PaymentController;
        $response = $facturador->reenviarFactura($this->pago->id_conciliacion);
        dd($response);

        if($response == true){
        
            // limpiar variables
            $this->limpiarVariables();

            $this->dispatchBrowserEvent('factura-reenviada', [

                'titleText' => 'Factura enviada',
                'confirmButtonText' => 'Cerrar',
                'icon'=> 'success',
            ]);

        } else {

            $this->dispatchBrowserEvent('swal:error', [

                'titleText' => 'Ups!',
                'text' => 'Ocurrió un error al generar la factura. Inténtelo nuevamente. Error: ' . $response,
                'confirmButtonText' => 'Cerrar',
                'icon'=> 'error',
            ]);
        }
    }
 

Error logged in console (chrome console)

 Uncaught (in promise) TypeError: Cannot read property 'redirect' of undefined
    at Component.value (index.js:263)
    at Component.value (index.js:248)
    at Connection.value (index.js:7)
    at index.js:58
 

If you need more info let me know.
Any help would be very appreciated.
Thanks in advance.

EDIT

This is the main page where i call the livewire component

 @extends('layout.master_vp_2')

@section('titulo', 'Estado de tu pago')

@push('plugin-styles')
  <link href="{{ asset('assets/plugins/sweetalert2/sweetalert2.min.css') }}" rel="stylesheet" />
@endpush

@section('content')
  @livewire('estado-pago', ['id_pago' => $id_pago, 'estado' => $estado])
@endsection

@push('plugin-scripts')
  <script type="text/javascript" src="{{ asset('assets/plugins/sweetalert2/sweetalert2.min.js') }}"></script>
@endpush

@push('custom-scripts')
  <script type="text/javascript" src="{{ asset('assets/js/vp_estado_pago.js') }}"></script>
@endpush
 

Это мой файл с лезвием

 <div>
    @if ($pago->forma_pago == 'Transferencia' amp;amp; $pago->estado == 'En proceso')
        <div class="row align-items-center h-100">
            <div class="jumbotron jumbotron-fluid mx-auto bg-white ">
                <div class="container align-items-center text-center p-5">

                    @if ($pago->comprobante_url == null)

                        <svg class="w-40 text-success" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path></svg>
                        <h1 class="display-2 my-3 font-weight-bold">¡Casi listo!</h1>
                        <p class="lead my-3 text-muted">¡Hola, {{ $nombre_usuario}}!, Puedes cargar tu <b>comprobante de pago</b> por <b>Transferencia electrónica</b> aqui debajo. Recuerda que debe ser <b>legible, menor a 1MB y en formato .jpeg, .png o .svg</b></p>
                        <button wire:click="redireccionTransferencia" class="btn btn-primary my-3">Ver instrucciones</button>
                        <button data-toggle="modal" data-target="#modal_cargar_comprobante" class="btn btn-primary my-3">Cargar comprobante</button>
                    
                    @else

                        @if ($transacciones !== null)

                        <div class="text-warning">
                            <svg class="w-40" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path></svg>
                        </div>
                        <div class="alert alert-warning text-center" role="alert" id="alerta_transacciones">
                            <h4 class="alert-heading">{{ $transacciones->movimiento }}</h4>
                            <hr>
                            <p class="mb-0">{{ $transacciones->comentarios }}</p>
                        </div>
                        <hr>
                        <img class="img-fluid" src="{{ url($pago->comprobante_url) }}" alt="comprobante_pago">
                        <hr>
                        <button data-toggle="modal" data-target="#modal_cargar_comprobante" class="btn btn-primary my-3">Cargar nuevo comprobante</button>
                        
                        @else
                            <svg class="w-40" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path></svg>
                            <h1 class="display-2 my-3 font-weight-bold">¡Listo!</h1>
                            <p class="lead my-3 text-muted">¡Bien, {{ $nombre_usuario}}!, Tu comprobante se encuentra en revisión para la aplicación de tu pago. consulta a las autoridades competentes para más información.</b></p>                      
                            <button data-toggle="modal" data-target="#modal_cargar_comprobante" class="btn btn-primary my-3">Cargar nuevo comprobante</button>
                       
                        @endif

                    @endif
                </div>
            </div>
        </div>
    @elseif($pago->forma_pago == 'Paypal' || ($pago->forma_pago == 'Transferencia' amp;amp; $pago->estado == 'Pagado'))
        <div class="row align-items-center h-100">
            <div class="jumbotron jumbotron-fluid mx-auto bg-white">
                <div class="container align-items-center text-center p-5">
                    @if ($pago->estado == 'Pagado')

                        <svg class="w-40 text-success" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path></svg>
                        <h1 class="display-2 my-3 font-weight-bold">¡Muchas gracias!</h1>
                        <p class="lead my-3 text-muted">Su pago ha sido completado con éxito.</p>

                        @if($pago->id_factura == null)
                            <button data-toggle="modal" data-target="#modal_generar_factura" role="button" class="btn btn-primary my-3 my-3">Facturar Pago</button>
                            <br>

                        @else
                            <p class="lead my-3 text-muted">¿No ha recibido su factura?</p>
                            <div class="input-group mb-3">
                                <input type="email" class="form-control" placeholder="Correo de destino" aria-label="Correo de destino" aria-describedby="ingresar correo">
                                <div class="input-group-append">
                                    <button class="btn btn-primary" type="button">Reenviar factura</button>
                                </div>
                            </div>
                            @error('correo')
                                <small class="text-primary">{{ $message }}</small>
                            @enderror
                            <br>
                        @endif

                        <a href="{{ route('vp_franquicias', ['codigo_franquicia' => 'TLA-ATI'] )}}" class="text-muted">
                            <i data-feather="arrow-left" class="icon-md mr-2"></i>
                            Regresar a página principal
                        </a>
                    
                    @elseif ($pago->estado == 'Cancelado')
                        <svg class="w-40 text-primary" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M13.477 14.89A6 6 0 015.11 6.524l8.367 8.368zm1.414-1.414L6.524 5.11a6 6 0 018.367 8.367zM18 10a8 8 0 11-16 0 8 8 0 0116 0z" clip-rule="evenodd"></path></svg>
                        <h1 class="display-2 my-3 font-weight-bold">Pago no procesado</h1>
                        <p class="lead my-3 text-muted">Su proceso de pago ha sido cancelado. Inténtelo nuevamente.</p>
                        <button wire:click="paginaCompletar" role="button" class="btn btn-primary my-3">Regresar a página principal</button>
                    
                    @elseif ($pago->estado == 'Fallido')
                        <svg class="w-40 text-primary" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M13.477 14.89A6 6 0 015.11 6.524l8.367 8.368zm1.414-1.414L6.524 5.11a6 6 0 018.367 8.367zM18 10a8 8 0 11-16 0 8 8 0 0116 0z" clip-rule="evenodd"></path></svg>
                        <h1 class="display-2 my-3 font-weight-bold">Ups!</h1>
                        <p class="lead my-3 text-muted">Ocurrió un problema al completar el pago. Póngase en contacto con el equipo de RegionAdmin para más información.</p>
                        <p class="lead my-3 text-muted">{{ $estado }}</p>
                        <button wire:click="paginaCompletar" role="button" class="btn btn-primary my-3">Regresar a página principal</button>
                    
                    @else
                        <svg class="w-40 text-primary" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path></svg>
                        <h1 class="display-2 my-3 font-weight-bold">Ups!</h1>
                        <p class="lead my-3 text-muted">Ocurrió un problema al completar el pago. Póngase en contacto con el equipo de RegionAdmin para más información.</p>
                        <button wire:click="paginaCompletar" role="button" class="btn btn-primary my-3">Regresar a página principal</button>
                    @endif
                </div>
            </div>
        </div>
    @endif

    <!-- Modal cargarComprobante -->
    <div wire:ignore.self class="modal fade" id="modal_cargar_comprobante" tabindex="-1" role="dialog" aria-labelledby="modal_cargar_comprobante_titulo" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modal_cargar_comprobante_titulo">Cargar comprobante</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">amp;times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <h6 class="card-subtitle mb-2 text-muted font-weight-light">Sube tu comprobante dando click en el boton seleccionar archivo</h6>
                    @if ($errors->any())
                        <div class="alert alert-danger">
                            <ul>
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif
                    <h6 class="card-description mb-2 text-muted font-weight-light">Recuerda que debe de ser legible, no exceder más de 1MB y ser en formato .jpeg, .jpg, .png o .svg</h6>
                    @if ($photo)
                        <p class="text-muted"><strong>Imagen cargada</strong></p>
                        <img src="{{ $photo->temporaryUrl() }}" class="img-fluid">
                    @endif
                    <div class="custom-file">
                        <label for="photo" class="custom-file-label"><strong>Comprobante de pago</strong></label>
                        <input wire:model="photo" type="file" class="custom-file-input" id="photo">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
                    <button type="button" class="btn btn-primary" wire:click="cargarComprobantePago">Cargar</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal facturacion -->
    <div wire:ignore.self class="modal fade" id="modal_generar_factura" tabindex="-1" role="dialog" aria-labelledby="modal_generar_factura_titulo" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modal_generar_factura_titulo">Generar factura</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">amp;times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <h6 class="card-subtitle mb-2 text-red">Ingresa los siguientes datos para generar tu factura</h6>
                    <div class="card">
                        <div class="card-header">
                            @if ($errors->any())
                                <div class="alert alert-danger">
                                    <ul>
                                        @foreach ($errors->all() as $error)
                                            <li>{{ $error }}</li>
                                        @endforeach
                                    </ul>
                                </div>
                            @endif
                        </div>
                        <div class="card-body">
                            <form>
                                <fieldset>
                                    <legend>Datos de facturación</legend>
                                    <div class="form-group">
                                        <label for="rfc"><strong>RFC</strong></label>
                                        <input wire:model="rfc" type="text" class="form-control" id="rfc" placeholder="EXAM010101ABC">
                                    </div>
                                    <div class="form-group">
                                        <label for="razon_social"><strong>Razón social</strong></label>
                                        <input wire:model="razon_social" type="text" class="form-control" id="razon_social" placeholder="regionadmin inc.">
                                    </div>
                                    <div class="form-group">
                                        <label for="correo"><strong>Correo electrónico</strong></label>
                                        <input wire:model="correo" type="email" class="form-control" id="correo" placeholder="name@example.com">
                                    </div>
                                    <div class="form-group">
                                        <label for="codigo_postal"><strong>Código postal</strong></label>
                                        <input wire:model="codigo_postal" type="text" class="form-control" id="codigo_postal" placeholder="45123">
                                    </div>
                                </fieldset>
                                <fieldset>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="checkbox" id="actualizar_direccion" wire:model="actualizar_direccion">
                                        <label class="form-check-label" for="actualizar_direccion">Actualizar datos de facturación</label>
                                    </div>
                                </fieldset>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
                    <button type="button" class="btn btn-primary" wire:click="generarFactura">Generar y enviar factura</button>
                </div>
            </div>
        </div>
    </div>
</div>
 

Также я заметил и остальные мои действия (ака. провод:щелчок и другой призыв к действию в режиме реального времени) работают должным образом. Единственный, который не работает, — это тот, который вызывает функцию reenviarFactura.

Комментарии:

1. Можете ли вы добавить компонент лезвия livewire? И было бы неплохо увидеть место, в которое вы вставляете файл JS