You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:解决JS向Livewire组件传值时的emit函数报错问题

JavaScript向Livewire组件传递变量失败的问题

我尝试了数小时将变量从JavaScript文件传递到Livewire组件,但始终失败,以下是我的尝试及报错:

尝试的代码与报错

第一种尝试

Livewire.emit('handleValue', value);

报错信息:

Uncaught (in promise) TypeError: Livewire.emit is not a function

第二种尝试

window.livewire.emit('handleValue', value);

报错信息:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'emit')

我的配置信息

布局文件(app.layout)脚本部分

...
<!-- Scripts -->
    @livewireScripts
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>

JS文件路径

public/js/clientMovement/googleAutocompleteField.js

更新的代码内容

完整JS文件代码

function initMap() {
const buero = "/*Adresse*/";
const vonStrasse = document.getElementById("vonStrasse").value;
const vonStadt = document.getElementById("vonStadt").value;
const vonPLZ = document.getElementById("vonPLZ").value;
const nachStrasse = document.getElementById("nachStrasse").value;
const nachStadt = document.getElementById("nachStadt").value;
const nachPLZ = document.getElementById("nachPLZ").value;
const distanceInputField = document.getElementById("distance");
const distanceClientFromTo = document.getElementById("kundeKm");
const distanceKm = document.getElementById("gesamtKm");

const clientAddressFrom = vonStrasse + ', ' + vonPLZ + ' ' + vonStadt;
const clientAddressTo = nachStrasse + ', ' + nachPLZ + ' ' + nachStadt;


const request1 = {
    origins: [buero],
    destinations: [clientAddressFrom],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false,
};

const request2 = {
    origins: [clientAddressFrom],
    destinations: [clientAddressTo],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false,
};

const request3 = {
    origins: [clientAddressTo],
    destinations: [buero],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false,
};


// 获取三段路线的距离矩阵响应
getDistanceMatrix(request1, function (response1) {
    getDistanceMatrix(request2, function (response2) {
        getDistanceMatrix(request3, function (response3) {
            // 合并三段路线的距离
            const totalDistance =
                response1.rows[0].elements[0].distance.value +
                response2.rows[0].elements[0].distance.value +
                response3.rows[0].elements[0].distance.value;

            const clientFromToDiestance =
                response2.rows[0].elements[0].distance.value;

            distanceInputField.value = totalDistance / 1000;
            distanceKm.value = totalDistance / 1000;
            distanceClientFromTo.value = clientFromToDiestance / 1000;

            const duration1 = response1.rows[0].elements[0].duration.value;
            const duration2 = response2.rows[0].elements[0].duration.value;
            const duration3 = response3.rows[0].elements[0].duration.value;

            totalDurationInSeconds = duration1 + duration2 + duration3;

            const totalDurationHours = totalDurationInSeconds / 3600;
            const roundedTotalDuration = roundToTwoDecimalPlaces(totalDurationHours);

            fahrtzeit.value = roundedTotalDuration;
            passValueToLivewire(roundedTotalDuration);
        });
    });
});
}

function passValueToLivewire(value) {
console.log(value);
Livewire.emit('handleValue', value);
}

Livewire组件代码

protected $listeners = ['handleValue'];
public function handleValue($value)
{
    // 处理传递过来的变量
}

解决方法

1. 调整脚本加载顺序

你的布局中@livewireScripts在@vite之前,Vite异步加载JS的特性可能导致自定义JS执行时Livewire还未初始化。将@livewireScripts移到@vite之后:

...
<!-- Scripts -->
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    @livewireScripts
</head>

2. 确保自定义JS正确引入

你的JS文件放在public/js/目录,Vite默认处理resources/js/下的文件,可通过两种方式修正:

  • 将googleAutocompleteField.js移动到resources/js/clientMovement/目录,然后在resources/js/app.js中导入:
    import './clientMovement/googleAutocompleteField.js';
    
  • 或者在布局中手动引入该JS文件,且放在@livewireScripts之后:
    @livewireScripts
    <script src="{{ asset('js/clientMovement/googleAutocompleteField.js') }}"></script>
    

3. 适配Livewire版本

如果使用Livewire 3,emit已被弃用,需改用dispatch:

function passValueToLivewire(value) {
    console.log(value);
    Livewire.dispatch('handleValue', value);
}

4. 验证组件监听有效性

确认Livewire组件已正确挂载到页面,可在组件的mount方法中添加日志,验证组件是否正常加载:

public function mount()
{
    logger('组件已挂载');
}

内容的提问来源于stack exchange,提问作者allstar_141

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 16:00:43