最近有個掃碼登入的業務需求,記錄一下laravel-echo使用心得,如有錯誤,輕噴。
環境說明
- 前端laravel-echo、pusher-js
- 後端laravel-websockets
laravel 文件程式碼
import Echo from "laravel-echo";
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-pusher-channels-key'
});
這裡把Pusher和Echo都暴露到window全域性環境,個人很不喜歡,所以進行改造了一下
改造後的程式碼
新建檔案laravel-echo.js
import Echo from 'laravel-echo'
import Pusher from "pusher-js"
/**
* pusher配置
*/
const pusherConfig = {
forceTLS: document.location.protocol === 'https:' ? true : false,
wsHost: window.location.hostname,
wssHost: window.location.hostname,
wsPort: 6001,
wssPort: 6001,
auth: {
headers: {}
},
disableStats: true
}
class LaravelEcho {
static instance = null
constructor() {
this.instance = new Echo({
client: new Pusher('saas', pusherConfig),
broadcaster: 'pusher'
})
}
setToken(token) {
this.instance.options.client.config.auth.headers.Authorization = `Bearer ${token}`
}
removeToken() {
this.instance.options.client.config.auth.headers = {}
}
}
export default new LaravelEcho()
使用範例
import LaravelEcho from '@/helpers/laravel-echo'
// 訂閱掃碼登入事件
LaravelEcho.instance.channel('auth').listen(`ScanQRCodeLoginEvent.${response.data.uuid}`, (e) => {
console.log(e)
})
本作品採用《CC 協議》,轉載必須註明作者和本文連結