2

我正在尝试将用户的地理坐标(纬度和经度)发送到 livewire 组件以加载附近的地方。但是我无法发送它,因为它们是 javascript 变量。问题是如何将 javascript 变量发送到 livewire 组件?

这是我到目前为止所做的。

# home.blade.php

@extends('layouts.app')

@section('content')
    <script>
        var latitude;
        var longitude;
        navigator.geolocation.getCurrentPosition(
            function success(pos) {
                var loc = pos.coords;
                latitude = loc.latitude;
                longitude = loc.longitude;
            }, 
            function error(err) {
                // console.warn(`ERROR(${err.code}): ${err.message}`);
                $.getJSON('https://ipinfo.io/geo', function(response) { 
                    var loc = response.loc.split(',');
                    latitude = parseFloat(loc[0]);
                    longitude = parseFloat(loc[1]);
                });
            }, options
        );
    </script>
    @livewire('nearby')
@endsection
@livewireScripts
# Nearby.php 

namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\WithPagination;
use App\Listing;

class Nearby extends Component
{
    use WithPagination;

    public function render()
    {
        $listings = Listing::paginate(9);
        return view('livewire.nearby', [
            'listings' => $listings
        ]);
    }
}
# nearby.blade.php - livewire blade

<div class="relative bg-gray-50 px-4 sm:px-6 lg:px-8">
    <div class="relative max-w-6xl mx-auto">
        <div class="mt-12 grid gap-5 max-w-lg mx-auto lg:grid-cols-3 lg:max-w-none">
            @foreach($listings as $listing)
                @include('components.listing',['listing'=>$listing])
            @endforeach
        </div>
        <div class="text-center mx-auto mt-3">
            {{ $listings->links() }}
        </div>
    </div>
</div>

4

1 回答 1

10

您需要从脚本全局发出一个事件。像这样:

 //emit this event inside your success function. pass latitude and longitude with the event 

  window.livewire.emit('set:latitude-longitude', latitude, longitude) 

之后,您可以从您的 livewire 组件类中收听此事件,如下所示:

  protected $listeners = [
        'set:latitude-longitude' => 'setLatitudeLongitude'
    ];

然后使用您的 livewire 组件类中的 setLatitudeLongitude 函数设置您传递的纬度。

public function setLatitudeLongitude($latitude, $longitude) 
{
   $this->latitude = $latitude;
   $this->longitude = $longitude;
}

如果您需要进一步解释,请告诉我:)

于 2020-04-24T07:45:47.327 回答