【问题标题】:alpineJS state in Laravel named route functionLaravel 中的 alpineJS 状态命名路由函数
【发布时间】:2021-06-17 15:46:52
【问题描述】:

我正在尝试使用 alpineJs 状态来创建我的 href url,但使用 Laravel 命名路由。

<div x-data="{ selectedSession: '{{$sessionsForDay->first()->id}}' }">
...
   <select id="session" name="session" x-on:change="$dispatch('selection-change', { value: $event.target.value })">

      @foreach($sessionsForDay as $sesson)
         <option @if ($loop->first) Selected @endif value="{{ $session->id }}">Session Name</option>
      @endfor

   </select>  
   
   <a 
    x-data="{ url: '{{ route('tours.booking', ['session_id' => $sessionsForDay->first()->id]) }}',  selectedSession: '{{ $sessionsForDay->first()->id }}' }"
    href="{{ route('tours.booking', ['session_id' => $sessionsForDay->first()->id]) }}" 
    x-on:selection-change.document="
    url = url.replace(selectedSession, $event.detail.value);
    selectedSession = $event.detail.value;"
    x-bind:href="url">
        Book Now
    </a>

当 $session->id 高于 10ish 时,代码当前正在运行,但低于 10ish 时会崩溃。控制台没有错误。只是 url 将在加载时保持第一个 url,但只有在我选择了其他会话之后。

【问题讨论】:

    标签: javascript laravel alpine.js


    【解决方案1】:

    我不建议使用动态变量来代替 url。 而是使用占位符:

    <a 
        x-data="{ baseUrl: '{{ route('tours.booking', ['session_id' => ':sessionId']) }}', url: {{ route('tours.booking', ['session_id' => $sessionsForDay->first()->id]) }}, selectedSession: '{{ $sessionsForDay->first()->id }}' }"
        href="{{ route('tours.booking', ['session_id' => $sessionsForDay->first()->id]) }}" 
        x-on:selection-change.document="
        url = baseUrl.replace(':sessionId', $event.detail.value);
        selectedSession = $event.detail.value;"
        x-bind:href="url">
            Book Now
    </a>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 2020-12-04
      • 1970-01-01
      • 2013-12-26
      • 2018-05-05
      相关资源
      最近更新 更多