Blazor 元件庫 BootstrapBlazor 中Editor元件介紹

jvx發表於2022-04-21

元件介紹

Editor元件是對Summernote 元件的二次封裝。

元件分為div模式和editor模式。

預設狀態下editor模式的元件樣子如下:

editor.png

其程式碼如下:

<Editor @bind-Value="@EditorValue" IsEditor="true"></Editor>

我們可以通過@bind-Value來繫結到欄位中.

元件的其他屬性

IsEditor:是否預設顯示為編輯器,預設為false,即顯示為一個div,只有在div被點選時才會顯示編輯器。

Height:元件高度,單位為px

ToolbarItems:自定義工具欄按鈕,具體的按鈕名參見Summernote的api文件。

一個例子是

<Editor IsEditor="true" ToolbarItems="@ToolbarItems"></Editor>
private List<object> ToolbarItems { get; } = new List<object>
        {
            new List<object> {"style", new List<string>() {"style"}},
            new List<object> {"font", new List<string>() {"bold", "underline", "clear"}}
        };

在這個例子中,我們只顯示了4個按鈕

editorbase.png

CustomerToolbarButtons:自定義按鈕,我們可以自定義工具欄的按鈕,用來完成部分我們自己的需求。

一個例子:

Editor:

<Editor IsEditor="true" OnClickButton="@PluginClick" CustomerToolbarButtons="@EditorPluginItems"></Editor>

EditorPluginItems的設定:

EditorPluginItems = new List<EditorToolbarButton>()
        {
            new EditorToolbarButton()
            {
                IconClass = "fa fa-pencil",
                ButtonName = "plugin1",
                Tooltip = Localizer["ToolTip1"]
            },
            new EditorToolbarButton()
            {
                IconClass = "fa fa-home",
                ButtonName = "plugin2",
                Tooltip = Localizer["ToolTip2"]
            }
        };

這裡我們增加了兩個按鈕,一個叫plugin1,一個叫plugin2

同時,在按鈕的點選事件中,我們可以獲取到Plugin的名字,用來區分是點選了哪個按鈕,並且返回的內容可以插入到Editor的游標對應位置。

private async Task<string?> PluginClick(string pluginItemName)
    {
        var ret = "";
        if (pluginItemName == "plugin1")
        {
            var op = new SwalOption()
            {
                Title = Localizer["SwalTitle"],
                Content = Localizer["SwalContent"]
            };
            if (await SwalService.ShowModal(op))
            {
                ret = Localizer["Ret1"];
            }
        }
        if (pluginItemName == "plugin2")
        {
            var op = new SwalOption()
            {
                Title = Localizer["Swal2Title"],
                Content = Localizer["Swal2Content"]
            };
            if (await SwalService.ShowModal(op))
            {
                ret = Localizer["Ret2"];
            }
        }
        return ret;
    }

新增後的樣子如下

editorplugin.png

第二行的兩個按鈕即為新增的按鈕,文字中的從plugin1返回的資料即為點選plugin1並確定後返回的資料。

從外部呼叫Editor的api

我們可以通過ref拿到Editor的例項,然後從外部直接呼叫Summernote的api。

拿到引用:

<Editor IsEditor="true" @ref="Editor"></Editor>

然後定義一個按鈕:

<Button OnClick="@(() => Editor.DoMethodAysnc("formatH2", ""))">將段落修改為 H2</Button>

即可將Editor的游標所在段落修改為H2

相關文章