jqhph / dcat-admin

🔥 基于 Laravel 的后台系统构建工具 (Laravel Admin),使用很少的代码快速构建一个功能完善的高颜值后台系统,内置丰富的后台常用组件,开箱即用,让开发者告别冗杂的HTML代码
http://www.dcatadmin.com
MIT License
3.81k stars 680 forks source link

后台的数据统计卡片。能配置websocket,SSE这种动态显示吗? #2106

Closed klphp closed 4 months ago

klphp commented 4 months ago

Description:

关于后台的数据统计卡片。能配置websocket,SSE这种动态显示吗。我现在的想法如下,不知能否实现:

<?php

namespace Kl\Admin\Metrics\Examples;

use Carbon\Carbon;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Card;
use Dcat\Admin\Widgets\Metrics\Line;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Dcat\Admin\Support\JavaScript;

class Channels extends Line
{

    protected array $items = [];

    /**
     * 初始化卡片内容
     *
     * @return void
     */
    protected function init()
    {
        parent::init();
        //获取所有频道
        $channels = Channel::where('status', Attrs::OK)->pluck('name')->toArray();
        array_unshift($channels, "All");
        $this->items = $channels;
        $this->title('当前在线人数');
        $this->height(280);
        $this->chartHeight(150);
        $this->dropdown($this->items);
    }

    public function addScript()
    {
        $baseURL = 'http://localhost/subscriptions';
        $url = $baseURL . '/public.newMessage';
        Admin::script(
        <<<JS
    $(function(){
       //获取token
        $.get('/get-token',function(token){
                const url = new URL('{$url}');
                url.searchParams.append('topic', 'public.newMessage');
                const eventSource = new EventSource(url);
                // 订阅消息
                eventSource.onmessage = function (data) {
                    //这里获取到数据发送ajax请求到handle,但是这个ajax请求地址怎么动态获取?
                };
        });
    })
JS
    );
    }

    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return mixed|void
     */
    public function handle(Request $request)
    {
    }

    /**
     * 设置卡片内容.
     *
     * @param string $content
     *
     * @return $this
     */
    public function withContent($content, $title)
    {
        $this->addScript();
        return $this->content(
            <<<HTML
<div class="d-flex justify-content-between align-items-center mt-1" style="margin-bottom: 2px">
    <h2 class="ml-1 font-lg-1">{$content}</h2>
    <span class="mb-0 mr-1 text-80">{$title}</span>
</div>
HTML
        );
    }
}

现在的问题1: addScript添加的js代码报错如下,不知道是不是添加js的方式不对。

(索引):1115 SyntaxError: "undefined" is not valid JSON
    at JSON.parse (<anonymous>)
    at t.value (apexcharts.min.js?v2.2.2-beta:6:74106)
    at t.value (apexcharts.min.js?v2.2.2-beta:6:74462)
    at new t (apexcharts.min.js?v2.2.2-beta:14:37026)
    at (索引):826:17
    at HTMLDocument.<anonymous> ((索引):831:3)
    at e (eval at <anonymous> (vendors.min.js?v2.2.2-beta:2:1), <anonymous>:1:29453)
    at t (eval at <anonymous> (vendors.min.js?v2.2.2-beta:2:1), <anonymous>:1:29755)

问题2:addScript 的代码中,ajax请求到handle的地址怎么动态获取。

刚用dcat-admin不久,很多不懂特此请教 。