🎨 Node-RED Dashboard 2.0 実践ガイド【応用編】
第1部 template

☁️ クラウドOK 環境とは?

このガイドでは、Dashboard 2.0の最も強力なウィジェットであるtemplateについて詳しく解説します。templateを使えば、Vue.jsとVuetifyを活用してカスタムウィジェットを自由に作成できます。

📌 このガイドで学べること:

📑 目次

  1. 🚀 サンプルフロー
  2. templateとは?
  3. 4つのテンプレートタイプ
  4. Vue.js Options API
  5. 組み込み変数とメソッド
  6. Vuetifyコンポーネント
  7. 実用的な使用パターン
  8. 実践演習
  9. まとめ
  10. トラブルシューティング
  11. 実務での活用例
  12. 追加リソース

🚀 まずサンプルフローをインポートしましょう!

📌 複数のフローを読み込むとき: このサイトの Dashboard 2.0 のフロー(サンプルフローと演習の解答例)は、すべて同じダッシュボード設定ノード(ui-base)を共有しています。2つ目以降のフローを読み込むと、「読み込もうとしているノードのいくつかは、既にワークスペース内に存在しています。」という通知が出ます。「コピーを読み込み」を選んでください。共有している設定ノードは既にあるものが使われ、どのフローのページも1つのダッシュボードにまとまります。ページはダッシュボードの左のメニューから選べます。ダッシュボード全体の見た目(ヘッダーやメニューの表示)は、最初に読み込んだフローの ui-base の設定になります。

ページが表示されないとき: ダッシュボードの設定ノード(ui-base)が2つ以上あると、そのうち1つのページしか表示されません。このサイトの以前の版のフローを読み込んでいると、この状態になります。以前の版のフローのタブを削除してから、エディタの メニュー → 設定ノード を開き、画面上部の「未使用」を選んで、どのノードからも使われていない ui-group・ui-page・ui-base・ui-theme を削除します。ui-group を消すとそれを使っていた ui-page が、ui-page を消すと ui-base が未使用になるので、未使用のものが無くなるまで繰り返してください。そのあとで、フローを読み込み直します。

📥 サンプルフローを試す手順:

  1. 下のフローJSONを「コピー」ボタンでコピー
  2. Node-REDエディタで メニュー → 読み込み を選択
  3. JSONをペーストして「読み込み」をクリック
  4. エディタ右上の「デプロイ」ボタンをクリック(クリックするまでフローは動きません)
  5. ブラウザでダッシュボード(http://localhost:1880/dashboard)を開き、左のメニューからページを選んで動作を確認

公式サンプルフロー

最初のサンプルフローは、Dashboard 2.0 の開発元である FlowFuse が公開している公式サンプルを、1つのタブにまとめたものです。出典は次の2か所です。

ノードの設定値とノードIDは公式のままです。このサイトで手を加えたのは次の点だけです。

例(出典・表示されるページ) 内容
design-patterns
GitHub examples・公式ドキュメント(Getting Started)
/dashboard/design-patterns
データの見せ方の2つの型を、2つのグループで比べます。
「Single Source of Truth」のグループは、スライダーの値をグラフと ui-template(Show to All)に送り、ダッシュボードを開いている全員に同じ値を表示します。ui-template へ送る前に、change ノードで msg._client(どの閲覧者からの操作かを表す情報)を消しています。
「Client-Driven」のグループは、ボタンやスライダーを操作した人の画面だけに値を表示します。ui-event はページを開いた閲覧者の情報を送り、ui-template がそれ(msg._client)を表示します。
閲覧者ごとに分かれるのは、ui-base の設定で ui-text と ui-template が「閲覧者ごとに送る」対象になっているときです。このフローの ui-base はそうなっていますが、先に別のフローを読み込んでいた場合は、その ui-base の設定が使われます。分かれないときは、エディタの Dashboard 2.0 サイドバーの「Client Data」タブにある「Accept Client Data」で、ui-text と ui-template にチェックを入れてデプロイしてください。違いは、ダッシュボードを2つのブラウザのタブで開くと確かめられます。
file-upload
公式ドキュメント(Template Examples)
/dashboard/entry
ui-template に、ファイルを選ぶ欄(Vuetify の v-file-input)と「Upload File」ボタンを置きます。ボタンを押すと、選んだファイルの中身を、名前・サイズ・種類(msg.file)とともに Node-RED へ送ります。function ノードで中身を文字列に変えて debug に出すので、テキストファイルで試すと中身が読めます。function ノードは公式のサンプルのままです。

ui-template の公式ドキュメントには、ほかにも表やグラフ、地図の例があります。このサイトでは、ほかのガイドの公式サンプルとページが重なるもの(ほかのガイドと同じページを使う例)や、別のノードの追加が必要なもの(地図)は収録していません。

📥 template 公式サンプルフローJSON(クリックで展開)
[ { "id": "dash2_template_official_tab", "type": "tab", "label": "template 公式サンプル", "disabled": false, "info": "", "env": [] }, { "id": "cmt_dash2_template_official_design_patterns", "type": "comment", "z": "dash2_template_official_tab", "name": "design-patterns(GitHub examples・公式ドキュメント Getting Started)", "info": "", "x": 320, "y": 60, "wires": [] }, { "id": "f385539f963b56ce", "type": "ui-text", "z": "dash2_template_official_tab", "group": "2b287eac8c5a64cd", "order": 2, "width": "3", "height": "1", "name": "", "label": "Your Latest Button Click:", "format": "{{msg.payload}}", "layout": "row-left", "style": false, "font": "", "fontSize": 16, "color": "#717171", "className": "", "x": 390, "y": 190, "wires": [] }, { "id": "ae23d23cc164d27a", "type": "ui-button", "z": "dash2_template_official_tab", "group": "2b287eac8c5a64cd", "name": "", "label": "Click Me!", "order": 3, "width": 0, "height": 0, "emulateClick": false, "tooltip": "", "color": "", "bgcolor": "", "className": "", "icon": "", "iconPosition": "left", "payload": "", "payloadType": "date", "topic": "topic", "topicType": "msg", "x": 200, "y": 190, "wires": [ [ "f385539f963b56ce" ] ] }, { "id": "a7d3cb9fc537d9bb", "type": "ui-slider", "z": "dash2_template_official_tab", "group": "8bee8ca608b26b77", "name": "", "label": "slider", "tooltip": "", "order": 1, "width": 0, "height": 0, "passthru": false, "outs": "all", "topic": "topic", "topicType": "msg", "thumbLabel": true, "min": 0, "max": 10, "step": 1, "className": "", "x": 250, "y": 330, "wires": [ [ "257625ee5df3a84e", "ea03c8bc066ebdf2", "5ef058757d792100" ] ] }, { "id": "257625ee5df3a84e", "type": "ui-chart", "z": "dash2_template_official_tab", "group": "8bee8ca608b26b77", "name": "", "label": "chart", "order": 3, "chartType": "line", "category": "topic", "categoryType": "msg", "xAxisProperty": "", "xAxisPropertyType": "msg", "xAxisType": "time", "yAxisProperty": "", "ymin": "", "ymax": "", "action": "append", "pointShape": "circle", "pointRadius": 4, "showLegend": true, "removeOlder": 1, "removeOlderUnit": "3600", "removeOlderPoints": "", "colors": [ "#1f77b4", "#aec7e8", "#ff7f0e", "#2ca02c", "#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5" ], "width": "9", "height": 8, "className": "", "textColorDefault": true, "gridColorDefault": true, "x": 430, "y": 390, "wires": [ [] ] }, { "id": "ce9b4c9ec9c4ed93", "type": "inject", "z": "dash2_template_official_tab", "name": "Clear Chart", "props": [ { "p": "payload" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "[]", "payloadType": "json", "x": 230, "y": 390, "wires": [ [ "257625ee5df3a84e" ] ] }, { "id": "8aefa358fdb6e177", "type": "ui-event", "z": "dash2_template_official_tab", "ui": "c2e1aa56f50f03bd", "name": "", "x": 200, "y": 150, "wires": [ [ "0b8294025998e4be" ] ] }, { "id": "0b8294025998e4be", "type": "ui-template", "z": "dash2_template_official_tab", "group": "2b287eac8c5a64cd", "page": "", "ui": "", "name": "", "order": 1, "width": 0, "height": 0, "head": "", "format": "<template>\n <strong>msg._client:</strong>\n <pre>{{ msg._client }}</pre>\n</template>", "storeOutMessages": true, "passthru": true, "resendOnRefresh": true, "templateScope": "local", "className": "", "x": 340, "y": 150, "wires": [ [] ] }, { "id": "c0a2283e528e663e", "type": "comment", "z": "dash2_template_official_tab", "name": "Client-Defined Data", "info": "", "x": 230, "y": 110, "wires": [] }, { "id": "c999e4c44afd670c", "type": "comment", "z": "dash2_template_official_tab", "name": "Shared Data (All Clients)", "info": "", "x": 250, "y": 270, "wires": [] }, { "id": "6de64b0ab3a086ed", "type": "ui-template", "z": "dash2_template_official_tab", "group": "8bee8ca608b26b77", "page": "", "ui": "", "name": "Show to All", "order": 2, "width": 0, "height": 0, "head": "", "format": "<template>\n <strong>Shared Slider Value:</strong>\n <pre>{{ msg.payload }}</pre>\n</template>", "storeOutMessages": true, "passthru": true, "resendOnRefresh": true, "templateScope": "local", "className": "", "x": 630, "y": 330, "wires": [ [] ] }, { "id": "ea03c8bc066ebdf2", "type": "change", "z": "dash2_template_official_tab", "name": "", "rules": [ { "t": "delete", "p": "_client", "pt": "msg" } ], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 450, "y": 330, "wires": [ [ "6de64b0ab3a086ed" ] ] }, { "id": "5ef058757d792100", "type": "ui-template", "z": "dash2_template_official_tab", "group": "2b287eac8c5a64cd", "page": "", "ui": "", "name": "Client-Driven", "order": 2, "width": "3", "height": "1", "head": "", "format": "<template>\n Client Specific Slider: {{ msg.payload }}\n</template>", "storeOutMessages": true, "passthru": true, "resendOnRefresh": true, "templateScope": "local", "className": "", "x": 630, "y": 190, "wires": [ [] ] }, { "id": "cmt_dash2_template_official_file_upload", "type": "comment", "z": "dash2_template_official_tab", "name": "file-upload(公式ドキュメント Template Examples)", "info": "", "x": 320, "y": 470, "wires": [] }, { "id": "ac0d56d388a4daa4", "type": "ui-template", "z": "dash2_template_official_tab", "group": "44010f4b04014d29", "page": "", "ui": "", "name": "Binary File Upload", "order": 0, "width": 0, "height": 0, "head": "", "format": "<template>\n <!-- Card for uploading binary file -->\n <v-card raised color=\"white\">\n <!-- Card Title -->\n <v-card-title>Upload binary file to Node-Red</v-card-title>\n <br>\n <v-card-text>\n <!-- File Input -->\n <v-file-input label=\"Click here to select a file\" show-size v-model=\"uploadFile\">\n </v-file-input>\n <!-- Progress Indicator -->\n <div>Progress: {{ progress }} bytes loaded</div>\n </v-card-text>\n <v-card-actions>\n <v-spacer></v-spacer>\n <!-- Upload Button -->\n <v-btn right @click=\"startUpload\">Upload File</v-btn>\n </v-card-actions>\n </v-card>\n</template>\n\n<script>\n export default {\n data() {\n return {\n uploadFile: null, // Holds the selected file\n progress: 0 // Progress indicator for file upload\n }\n },\n methods: {\n // Method triggered when Upload File button is clicked\n startUpload() {\n // Check if a file is selected\n if (!this.uploadFile) {\n console.warn('No file selected');\n return;\n }\n\n // Log the selected file information to console\n console.log('File selected:');\n console.log(this.uploadFile);\n\n // Create a FileReader instance to read the file\n const reader = new FileReader();\n\n // When the file is read, send it to Node-RED\n reader.onload = () => {\n // Prepare the payload to send\n const payload = {\n topic: 'upload', // Topic for Node-RED\n payload: this.uploadFile, // File content\n file: {\n name: this.uploadFile.name, // File name\n size: this.uploadFile.size, // File size\n type: this.uploadFile.type // File type\n }\n };\n \n // Send the payload to Node-RED (assuming 'send' method is defined)\n this.send(payload);\n };\n\n // Track progress of file reading\n reader.onprogress = (event) => {\n this.progress = event.loaded; // Update progress\n };\n\n // Read the file as an ArrayBuffer\n reader.readAsArrayBuffer(this.uploadFile);\n }\n },\n }\n</script>", "storeOutMessages": true, "passthru": true, "resendOnRefresh": true, "templateScope": "local", "className": "", "x": 200, "y": 520, "wires": [ [ "7c2cc0e98edc2535" ] ] }, { "id": "df9661cfece5ac80", "type": "debug", "z": "dash2_template_official_tab", "name": "debug 365", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "true", "targetType": "full", "statusVal": "", "statusType": "auto", "x": 680, "y": 520, "wires": [] }, { "id": "7c2cc0e98edc2535", "type": "function", "z": "dash2_template_official_tab", "name": "buffer2string", "func": "msg.payload = msg.payload.toString()\nreturn msg;\n", "outputs": 1, "timeout": 0, "noerr": 0, "initialize": "", "finalize": "", "libs": [], "x": 440, "y": 520, "wires": [ [ "df9661cfece5ac80" ] ] }, { "id": "c2e1aa56f50f03bd", "type": "ui-base", "name": "Dashboard", "path": "/dashboard", "includeClientData": true, "acceptsClientConfig": [ "ui-control", "ui-notification", "ui-text", "ui-template" ], "showPathInSidebar": false, "headerContent": "none", "navigationStyle": "default", "titleBarStyle": "default" }, { "id": "c2ff5ba1f92a0f0e", "type": "ui-theme", "name": "Default", "colors": { "surface": "#ffffff", "primary": "#0094ce", "bgPage": "#eeeeee", "groupBg": "#ffffff", "groupOutline": "#cccccc" }, "sizes": { "pagePadding": "12px", "groupGap": "12px", "groupBorderRadius": "4px", "widgetGap": "12px" } }, { "id": "0d92c765bfad87e6", "type": "ui-theme", "name": "Basic Blue Theme", "colors": { "surface": "#4d58ff", "primary": "#0094ce", "bgPage": "#eeeeee", "groupBg": "#ffffff", "groupOutline": "#cccccc" }, "sizes": { "pagePadding": "12px", "groupGap": "12px", "groupBorderRadius": "4px", "widgetGap": "12px" } }, { "id": "1a43c75e8780fe2b", "type": "ui-page", "name": "Design Pattern Examples", "ui": "c2e1aa56f50f03bd", "path": "/design-patterns", "icon": "home", "layout": "grid", "theme": "c2ff5ba1f92a0f0e", "order": 1, "className": "", "visible": "true", "disabled": "false" }, { "id": "dd8d2662278f4f72", "type": "ui-page", "name": "Data Entry New", "ui": "c2e1aa56f50f03bd", "path": "/entry", "icon": "note-multiple", "layout": "grid", "theme": "0d92c765bfad87e6", "order": 1, "className": "", "visible": "true", "disabled": "false" }, { "id": "2b287eac8c5a64cd", "type": "ui-group", "name": "Design Pattern - Client Driven", "page": "1a43c75e8780fe2b", "width": "9", "height": "1", "order": -1, "showTitle": true, "className": "", "visible": "true", "disabled": "false" }, { "id": "8bee8ca608b26b77", "type": "ui-group", "name": "Design Pattern - Single Source of Truth", "page": "1a43c75e8780fe2b", "width": "9", "height": "1", "order": -1, "showTitle": true, "className": "", "visible": "true", "disabled": "false" }, { "id": "44010f4b04014d29", "type": "ui-group", "name": "Binary Upload", "page": "dd8d2662278f4f72", "width": "6", "height": "1", "order": -1, "showTitle": true, "className": "", "visible": "true", "disabled": "false" } ]

応用(サイト独自): 全パターンのサンプル

ここから先は公式サンプルではなく、本サイトが用意した応用教材です。このガイドで説明する ui-template の使い方を、1つのタブにまとめています。ダッシュボードでは /dashboard/template-samples に表示されます。1章以降の説明は、このフローを例に進めます。

📋 応用フローJSON(クリックで展開)
[ { "id": "template_sample_tab", "type": "tab", "label": "ui-template サンプル", "disabled": false, "info": "Dashboard 2.0 ui-templateの各種サンプル" }, { "id": "comment_basic", "type": "comment", "z": "template_sample_tab", "name": "━━━ 📌 基本的なカスタムウィジェット ━━━", "info": "", "x": 200, "y": 40, "wires": [] }, { "id": "template_counter", "type": "ui-template", "z": "template_sample_tab", "group": "template_group_basic", "page": "", "ui": "", "name": "カウンター", "order": 1, "width": 0, "height": 0, "format": "<template>\n <div class=\"counter-widget\">\n <h3>カウンター</h3>\n <div class=\"count-display\">{{ count }}</div>\n <div class=\"button-group\">\n <v-btn color=\"error\" @click=\"decrement\">-</v-btn>\n <v-btn color=\"primary\" @click=\"increment\">+</v-btn>\n <v-btn color=\"secondary\" @click=\"reset\">リセット</v-btn>\n </div>\n <p class=\"info\">合計: {{ formattedCount }}</p>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n count: 0\n };\n },\n computed: {\n formattedCount() {\n return this.count.toLocaleString() + ' 回';\n }\n },\n methods: {\n increment() {\n this.count++;\n this.sendCount();\n },\n decrement() {\n if (this.count > 0) this.count--;\n this.sendCount();\n },\n reset() {\n this.count = 0;\n this.sendCount();\n },\n sendCount() {\n this.send({ payload: this.count, topic: 'counter' });\n }\n },\n watch: {\n msg(newMsg) {\n if (typeof newMsg.payload === 'number') {\n this.count = newMsg.payload;\n }\n }\n }\n}\n</script>\n\n<style scoped>\n.counter-widget {\n text-align: center;\n padding: 20px;\n}\n.count-display {\n font-size: 48px;\n font-weight: bold;\n color: #b92d5d;\n margin: 20px 0;\n}\n.button-group {\n display: flex;\n gap: 10px;\n justify-content: center;\n}\n.info {\n margin-top: 15px;\n color: #666;\n}\n</style>", "passthru": true, "templateScope": "local", "className": "", "x": 140, "y": 100, "wires": [ [ "debug_counter" ] ] }, { "id": "debug_counter", "type": "debug", "z": "template_sample_tab", "name": "カウンター出力", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "payload", "targetType": "msg", "statusVal": "payload", "statusType": "auto", "x": 340, "y": 100, "wires": [] }, { "id": "inject_counter_set", "type": "inject", "z": "template_sample_tab", "name": "50に設定", "props": [ { "p": "payload" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "50", "payloadType": "num", "x": 140, "y": 160, "wires": [ [ "template_counter" ] ] }, { "id": "comment_msg_display", "type": "comment", "z": "template_sample_tab", "name": "━━━ 📨 メッセージ受信・表示 ━━━", "info": "", "x": 180, "y": 240, "wires": [] }, { "id": "template_msg_display", "type": "ui-template", "z": "template_sample_tab", "group": "template_group_basic", "page": "", "ui": "", "name": "メッセージ表示", "order": 2, "width": 0, "height": 0, "format": "<template>\n <v-card class=\"msg-card\">\n <v-card-title>📨 受信メッセージ</v-card-title>\n <v-card-text>\n <div v-if=\"lastMsg\">\n <p><strong>Payload:</strong> {{ lastMsg.payload }}</p>\n <p><strong>Topic:</strong> {{ lastMsg.topic || '(なし)' }}</p>\n <p><strong>受信時刻:</strong> {{ receivedTime }}</p>\n </div>\n <div v-else class=\"no-msg\">\n メッセージを待機中...\n </div>\n </v-card-text>\n </v-card>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n lastMsg: null,\n receivedTime: ''\n };\n },\n watch: {\n msg(newMsg) {\n this.lastMsg = newMsg;\n this.receivedTime = new Date().toLocaleTimeString('ja-JP');\n }\n }\n}\n</script>\n\n<style scoped>\n.msg-card {\n margin: 10px;\n}\n.no-msg {\n color: #999;\n font-style: italic;\n}\n</style>", "passthru": true, "templateScope": "local", "className": "", "x": 160, "y": 300, "wires": [ [] ] }, { "id": "inject_msg_hello", "type": "inject", "z": "template_sample_tab", "name": "Hello", "props": [ { "p": "payload" }, { "p": "topic", "vt": "str" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "greeting", "payload": "Hello, Dashboard!", "payloadType": "str", "x": 130, "y": 360, "wires": [ [ "template_msg_display" ] ] }, { "id": "inject_msg_data", "type": "inject", "z": "template_sample_tab", "name": "センサーデータ", "props": [ { "p": "payload" }, { "p": "topic", "vt": "str" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "sensor", "payload": "{\"temperature\":25.5,\"humidity\":60}", "payloadType": "json", "x": 160, "y": 400, "wires": [ [ "template_msg_display" ] ] }, { "id": "comment_file_upload", "type": "comment", "z": "template_sample_tab", "name": "━━━ 📁 ファイルアップロード ━━━", "info": "", "x": 180, "y": 480, "wires": [] }, { "id": "template_file_upload", "type": "ui-template", "z": "template_sample_tab", "group": "template_group_advanced", "page": "", "ui": "", "name": "ファイルアップロード", "order": 1, "width": 0, "height": 0, "format": "<template>\n <v-card class=\"upload-card\">\n <v-card-title>📁 ファイルアップロード</v-card-title>\n <v-card-text>\n <div>\n <v-file-input\n v-model=\"selectedFile\"\n label=\"ファイルを選択\"\n prepend-icon=\"mdi-paperclip\"\n show-size\n @change=\"onFileSelect\"\n />\n </div>\n <div v-if=\"uploading\" class=\"my-3\">\n <v-progress-linear\n :model-value=\"progress\"\n color=\"primary\"\n height=\"20\"\n >\n {{ progress }}%\n </v-progress-linear>\n </div>\n <div class=\"mt-3\">\n <v-btn\n color=\"primary\"\n :disabled=\"!selectedFile || uploading\"\n @click=\"uploadFile\"\n block\n >\n アップロード\n </v-btn>\n </div>\n </v-card-text>\n </v-card>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n selectedFile: null,\n uploading: false,\n progress: 0\n };\n },\n methods: {\n onFileSelect(e) {\n this.progress = 0;\n },\n uploadFile() {\n if (!this.selectedFile) return;\n \n this.uploading = true;\n const reader = new FileReader();\n \n reader.onprogress = (e) => {\n if (e.lengthComputable) {\n this.progress = Math.round((e.loaded / e.total) * 100);\n }\n };\n \n reader.onload = (e) => {\n this.send({\n payload: e.target.result,\n filename: this.selectedFile.name,\n size: this.selectedFile.size,\n type: this.selectedFile.type\n });\n this.uploading = false;\n this.progress = 100;\n };\n \n reader.readAsArrayBuffer(this.selectedFile);\n }\n }\n}\n</script>\n\n<style scoped>\n.upload-card {\n margin: 10px;\n}\n</style>", "passthru": true, "templateScope": "local", "className": "", "x": 180, "y": 540, "wires": [ [ "debug_file" ] ] }, { "id": "debug_file", "type": "debug", "z": "template_sample_tab", "name": "ファイル情報", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "true", "targetType": "full", "statusVal": "filename", "statusType": "auto", "x": 390, "y": 540, "wires": [] }, { "id": "comment_star_rating", "type": "comment", "z": "template_sample_tab", "name": "━━━ ⭐ 星評価ウィジェット ━━━", "info": "", "x": 180, "y": 620, "wires": [] }, { "id": "template_star_rating", "type": "ui-template", "z": "template_sample_tab", "group": "template_group_advanced", "page": "", "ui": "", "name": "星評価", "order": 2, "width": 0, "height": 0, "format": "<template>\n <div class=\"rating-widget\">\n <h3>⭐ 評価してください</h3>\n <v-rating\n v-model=\"rating\"\n color=\"amber\"\n hover\n length=\"5\"\n size=\"x-large\"\n @update:model-value=\"onRatingChange\"\n />\n <p class=\"rating-text\">{{ ratingText }}</p>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n rating: 0\n };\n },\n computed: {\n ratingText() {\n const texts = ['未評価', '不満', 'やや不満', '普通', '満足', '大満足'];\n return texts[this.rating] || '未評価';\n }\n },\n methods: {\n onRatingChange(value) {\n this.send({ \n payload: value, \n topic: 'rating',\n text: this.ratingText\n });\n }\n },\n watch: {\n msg(newMsg) {\n if (typeof newMsg.payload === 'number') {\n this.rating = Math.min(5, Math.max(0, newMsg.payload));\n }\n }\n }\n}\n</script>\n\n<style scoped>\n.rating-widget {\n text-align: center;\n padding: 20px;\n}\n.rating-text {\n margin-top: 10px;\n font-size: 18px;\n color: #666;\n}\n</style>", "passthru": true, "templateScope": "local", "className": "", "x": 130, "y": 680, "wires": [ [ "debug_rating" ] ] }, { "id": "debug_rating", "type": "debug", "z": "template_sample_tab", "name": "評価出力", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "true", "targetType": "full", "statusVal": "payload", "statusType": "auto", "x": 300, "y": 680, "wires": [] }, { "id": "inject_rating_3", "type": "inject", "z": "template_sample_tab", "name": "3つ星に設定", "props": [ { "p": "payload" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "3", "payloadType": "num", "x": 150, "y": 740, "wires": [ [ "template_star_rating" ] ] }, { "id": "comment_chartjs", "type": "comment", "z": "template_sample_tab", "name": "━━━ 📊 外部ライブラリ(Chart.js) ━━━", "info": "", "x": 200, "y": 820, "wires": [] }, { "id": "template_chartjs", "type": "ui-template", "z": "template_sample_tab", "group": "template_group_advanced", "page": "", "ui": "", "name": "Chart.jsグラフ", "order": 3, "width": 6, "height": 6, "format": "<template>\n <v-card class=\"chart-card\">\n <v-card-title>📊 センサーデータ</v-card-title>\n <v-card-text>\n <div class=\"chart-wrapper\">\n <canvas ref=\"chartCanvas\"></canvas>\n </div>\n </v-card-text>\n </v-card>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n chart: null,\n chartData: [12, 19, 8, 15, 12, 8, 14]\n };\n },\n mounted() {\n this.loadChartJS();\n },\n methods: {\n loadChartJS() {\n if (window.Chart) {\n this.initChart();\n return;\n }\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/chart.js';\n script.onload = () => {\n this.initChart();\n };\n document.head.appendChild(script);\n },\n initChart() {\n const ctx = this.$refs.chartCanvas;\n if (!ctx) return;\n \n this.chart = new Chart(ctx, {\n type: 'line',\n data: {\n labels: ['月', '火', '水', '木', '金', '土', '日'],\n datasets: [{\n label: 'センサー値',\n data: this.chartData,\n borderColor: '#b92d5d',\n backgroundColor: 'rgba(185, 45, 93, 0.1)',\n fill: true,\n tension: 0.4\n }]\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n plugins: {\n legend: { position: 'top' }\n },\n scales: {\n y: { beginAtZero: true }\n }\n }\n });\n },\n updateChart(newData) {\n if (this.chart && Array.isArray(newData)) {\n this.chart.data.datasets[0].data = newData;\n this.chart.update();\n }\n }\n },\n watch: {\n msg(newMsg) {\n if (Array.isArray(newMsg.payload)) {\n this.updateChart(newMsg.payload);\n }\n }\n },\n beforeUnmount() {\n if (this.chart) {\n this.chart.destroy();\n }\n }\n}\n</script>\n\n<style scoped>\n.chart-card {\n margin: 10px;\n}\n.chart-wrapper {\n height: 280px;\n position: relative;\n}\n</style>", "passthru": true, "templateScope": "local", "className": "", "x": 160, "y": 880, "wires": [ [ "debug_chartjs" ] ] }, { "id": "debug_chartjs", "type": "debug", "z": "template_sample_tab", "name": "Chart出力", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "payload", "targetType": "msg", "x": 350, "y": 880, "wires": [] }, { "id": "inject_chartjs", "type": "inject", "z": "template_sample_tab", "name": "サンプルデータ", "props": [ { "p": "payload" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "[25, 18, 22, 30, 28, 20, 15]", "payloadType": "json", "x": 160, "y": 940, "wires": [ [ "template_chartjs" ] ] }, { "id": "comment_css", "type": "comment", "z": "template_sample_tab", "name": "━━━ 🎨 カスタムCSS ━━━", "info": "", "x": 160, "y": 1020, "wires": [] }, { "id": "template_custom_css", "type": "ui-template", "z": "template_sample_tab", "group": "", "page": "", "ui": "c2e1aa56f50f03bd", "name": "サイト全体CSS", "order": 0, "width": 0, "height": 0, "format": "<style>\n/* カスタムフォント */\n@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;700&display=swap');\n\n/* サイト全体のスタイル */\nbody {\n font-family: 'Noto Sans JP', sans-serif !important;\n}\n\n/* ナビゲーションバーのグラデーション */\n.v-toolbar {\n background: linear-gradient(90deg, #b92d5d 0%, #c00000 100%) !important;\n}\n\n/* カード影の強化 */\n.v-card {\n box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;\n}\n\n/* プライマリボタンのホバー効果 */\n.v-btn--variant-elevated:hover {\n transform: translateY(-2px);\n transition: transform 0.2s;\n}\n</style>", "passthru": true, "templateScope": "site:style", "className": "", "x": 160, "y": 1080, "wires": [ [] ] }, { "id": "c2e1aa56f50f03bd", "type": "ui-base", "name": "Part1 ui-template デモ", "path": "/dashboard", "appIcon": "", "includeClientData": true, "acceptsClientConfig": [ "ui-notification", "ui-control" ], "showPathInSidebar": false, "headerContent": "page", "navigationStyle": "default", "titleBarStyle": "default", "showReconnectNotification": true, "notificationDisplayTime": 1, "showDisconnectNotification": true, "allowInstall": false }, { "id": "template_ui_theme", "type": "ui-theme", "name": "Custom Theme", "colors": { "surface": "#ffffff", "primary": "#b92d5d", "bgPage": "#f5f5f5", "groupBg": "#ffffff", "groupOutline": "#e0e0e0" }, "sizes": { "pagePadding": "12px", "groupGap": "12px", "groupBorderRadius": "8px", "widgetGap": "12px", "density": "default" } }, { "id": "template_page", "type": "ui-page", "name": "Part1 デモ", "ui": "c2e1aa56f50f03bd", "path": "/template-samples", "icon": "mdi-code-tags", "layout": "grid", "theme": "template_ui_theme", "breakpoints": [ { "name": "Default", "px": 0, "cols": 3 }, { "name": "Tablet", "px": 576, "cols": 6 }, { "name": "Desktop", "px": 1024, "cols": 12 } ], "order": 1, "className": "", "visible": true, "disabled": false }, { "id": "template_group_basic", "type": "ui-group", "name": "📌 基本サンプル", "page": "template_page", "width": "6", "height": "-1", "order": 1, "showTitle": true, "groupType": "default", "className": "", "visible": true, "disabled": false }, { "id": "template_group_advanced", "type": "ui-group", "name": "🚀 高度なサンプル", "page": "template_page", "width": "6", "height": "-1", "order": 2, "showTitle": true, "groupType": "default", "className": "", "visible": true, "disabled": false } ]

🎯 1. templateとは?

🤔 「template」って何?

templateは、Dashboard 2.0で完全にカスタマイズされたウィジェットを作成できる最も強力なノードです。 日常生活で例えると、「DIY工房」のようなものです。他のウィジェットが「既製品の家具」だとすれば、templateは「自分で設計図を描いて、好きな材料で好きな家具を作れる工房」です。

🔧 DIY工房に例えると:

高度 template ウィジェット

Vue.jsとVuetifyを使って、完全にカスタマイズされたダッシュボードコンポーネントを作成できます。HTML、CSS、JavaScriptを組み合わせて、標準ウィジェットでは実現できない機能を実装できます。

📊 templateでできること

🎨 カスタムウィジェット

標準ウィジェットにない独自のUIコンポーネントを作成

例: 星評価、カラーピッカー、 ドラッグ&ドロップなど

🎭 カスタムCSS

ダッシュボード全体や特定ページのスタイルをカスタマイズ

例: テーマカラー変更、 フォント変更、レイアウト調整

📊 高度なデータ表示

Chart.jsやD3.jsを使った高度なグラフ・可視化

例: カスタムチャート、 ヒートマップ、3Dグラフ

🔗 外部ライブラリ連携

外部JavaScriptライブラリを読み込んで活用

例: Leaflet地図、 Three.js 3D表示など

動作を図で見る

ui-template ノードは、受け取った msg を自分で書いた部品に差し込んで表示し、部品の操作を msg にして送り出すこともできます。

payload: 25.3ui-template<p>{{ msg.payload }} ℃</p><button @click="send(…)">ダッシュボード25.3 ℃リセット押すと msg が出る
msg.payload が部品の中に表示され、send() で msg が出ていく

📋 2. 4つのテンプレートタイプ

templateには4つの異なるタイプがあり、それぞれ用途が異なります。

タイプ スコープ 用途 Group設定
Widget ウィジェット (UI) グループ内 カスタムウィジェットの作成 必須
CSS スコープCSS グループ内 特定グループのスタイル変更 必須
Page ページ (UI) ページ全体 ページ全体に表示するUI要素 ページ選択
Site サイト全体CSS 全ページ ダッシュボード全体のスタイル ui-base選択

Widget ウィジェット (UI) タイプ

最も一般的なタイプで、カスタムウィジェットを作成します。指定したグループ内に表示されます。

<template> <v-btn @click="onClick">カスタムボタン</v-btn> </template> <script> export default { methods: { onClick() { this.send({ payload: "クリックされました" }); } } } </script>

CSS スコープCSSタイプ

特定のグループやウィジェットのスタイルをカスタマイズします。<style>タグのみを記述します。

<style> /* グループ内のボタンの色を変更 */ .v-btn { background-color: #ff5722 !important; } /* 特定のクラスにスタイル適用 */ .my-custom-class { font-size: 18px; font-weight: bold; } </style>

Page ページ (UI) タイプ

ページ全体に表示されるUI要素を作成します。フッターやページ共通の要素に最適です。

<template> <div class="page-footer"> <p>© 2024 My Dashboard - ページ共通フッター</p> </div> </template> <style scoped> .page-footer { position: fixed; bottom: 0; width: 100%; background: #333; color: white; text-align: center; padding: 10px; } </style>

Site サイト全体CSSタイプ

ダッシュボード全体に適用されるCSSを定義します。テーマのカスタマイズに使用します。

<style> /* サイト全体のフォント変更 */ body { font-family: 'Noto Sans JP', sans-serif !important; } /* プライマリカラーの変更 */ :root { --v-primary-base: #b92d5d !important; } /* ナビゲーションバーのスタイル */ .v-app-bar { background: linear-gradient(90deg, #b92d5d, #c00000) !important; } </style>

🔹 ノード設定プロパティ

template(ui-template)はエディターが日本語化されている(ja ロケールあり)。ja 翻訳のない「Size」のみ「英語ラベル(日本語訳)」で示す。「種類」で選んだ適用範囲によって、対象を選ぶ欄(グループ/ページ/画面)が切り替わる。表はエディターの上から下への並びに沿う。

設定項目 説明 デフォルト
名前 フローエディター上でノードを識別する管理名。 (空)
種類 テンプレートの適用範囲。部品 (有効範囲-グループ)/部品 (有効範囲-ページ)/部品 (有効範囲-画面)/CSS (全てのページ)/CSS (単一のページ)。選んだ範囲で次の対象欄が変わる。 部品 (有効範囲-グループ)
グループ / ページ / 画面 「種類」に応じて切り替わる対象セレクタ。グループ範囲ならグループ、ページ範囲ならページ、画面範囲や全ページ CSS なら画面(UI Base)を選ぶ。 (必須)
Size(サイズ) グループ内で占める幅と高さ。0 で自動。部品(ウィジェット)範囲のときに使う。 自動
クラス 任意の CSS クラス名。 (空)
テンプレート 表示内容の本体。Vue.js の単一ファイルコンポーネント(template/script/style)または CSS を記述する。 (既定テンプレート)
入力メッセージをそのまま渡す 入力された msg を出力にもそのまま流すか(passthru)。 オン
更新時に最後の値を再度読み込む ダッシュボードを再読み込みしたとき、最後に受け取った値を復元するか(resendOnRefresh)。 オフ

⚡ 3. Vue.js Options API

templateでは、Vue.jsのOptions APIを使用してコンポーネントを構築します。以下のプロパティがサポートされています。

プロパティ 説明 使用例
data コンポーネント内で使用するデータを定義する関数 カウンター、状態管理
methods テンプレートやスクリプトから呼び出せる関数を定義 ボタンクリック処理
computed 他の変数から計算される値を定義 合計値、フォーマット済み文字列
watch 変数の変更を監視して処理を実行 msgの変更検知
mounted コンポーネントがロードされた時に実行 初期化処理
unmounted コンポーネントが削除される時に実行 クリーンアップ処理

💡 Vue.js Options APIの基本構造:

<template> <!-- HTMLテンプレート(Vue.jsディレクティブ使用可能)--> <div>{{ message }}</div> </template> <script> export default { data() { return { message: "Hello World", count: 0 }; }, computed: { doubleCount() { return this.count * 2; } }, methods: { increment() { this.count++; this.send({ payload: this.count }); } }, watch: { msg(newMsg) { // msgが変更された時の処理 this.message = newMsg.payload; } }, mounted() { // コンポーネントロード時の初期化 console.log("コンポーネントがマウントされました"); } } </script>

🔧 4. 組み込み変数とメソッド

📦 組み込み変数

変数 説明 使用例
msg Node-REDから受信した最新のメッセージ {{ msg.payload }}
this.$socket Socket.IO接続オブジェクト カスタムイベントリスナー
this.$route 現在のルート情報(URLパラメータなど) this.$route.query.param
this.id ウィジェットのユニークID ソケットイベント識別

📤 組み込みメソッド

メソッド 説明 使用例
this.send(msg) Node-REDフローにメッセージを送信 this.send({ payload: "データ" })
this.submit() フォームデータをNode-REDに送信 フォーム送信処理

📬 メッセージ受信の2つの方法

方法1: watchでmsgを監視

watch: { msg(newMsg) { // 新しいメッセージを受信した時 // 注意: 初回ロード時も呼び出される this.data = newMsg.payload; } }

方法2: Socket.IOイベントリスナー

mounted() { // 新しいメッセージ受信時のみ実行(初回ロード時は実行されない) this.$socket.on('msg-input:' + this.id, (msg) => { this.data = msg.payload; }); }, unmounted() { // クリーンアップ this.$socket.off('msg-input:' + this.id); }

⚠️ watchとSocket.IOの違い:

用途に応じて使い分けましょう。

🎨 5. Vuetifyコンポーネント

templateでは、Vuetifyコンポーネントライブラリが標準で利用可能です。豊富な既製コンポーネントを使って、プロフェッショナルなUIを簡単に構築できます。

🔧 よく使うVuetifyコンポーネント

v-btn(ボタン)

<v-btn color="primary" @click="onClick"> クリック </v-btn>

v-text-field(テキスト入力)

<v-text-field v-model="inputText" label="入力してください" />

v-select(セレクトボックス)

<v-select v-model="selected" :items="options" label="選択" />

v-slider(スライダー)

<v-slider v-model="value" :min="0" :max="100" label="値" />

v-card(カード)

<v-card> <v-card-title>タイトル</v-card-title> <v-card-text>内容</v-card-text> </v-card>

v-file-input(ファイル入力)

<v-file-input v-model="file" label="ファイル選択" @change="onFileChange" />

💡 Vuetifyコンポーネント一覧:

全コンポーネントは Vuetify公式ドキュメント で確認できます。

🎯 7. 実用的な使用パターン

パターン1: 基本的なカスタムボタン

用途: シンプルなカスタムボタンでNode-REDにメッセージを送信

template
カスタムボタン
→ Debug
<template> <v-btn color="primary" size="large" @click="onClick"> 送信 </v-btn> </template> <script> export default { methods: { onClick() { this.send({ payload: "ボタンがクリックされました" }); } } } </script>

パターン2: データ受信・表示ウィジェット

用途: Node-REDからのメッセージを受信して表示

Inject → template
データ表示
<template> <v-card> <v-card-title>受信データ</v-card-title> <v-card-text> <p v-if="msg">{{ msg.payload }}</p> <p v-else>データ待機中...</p> </v-card-text> </v-card> </template>

パターン3: 双方向バインディング(入力フォーム)

用途: ユーザー入力を受け取り、Node-REDに送信

template
入力フォーム
→ Debug
<template> <div> <v-text-field v-model="name" label="お名前" /> <v-text-field v-model="email" label="メールアドレス" type="email" /> <v-btn color="primary" @click="submit">送信</v-btn> </div> </template> <script> export default { data() { return { name: '', email: '' }; }, methods: { submit() { this.send({ payload: { name: this.name, email: this.email } }); } } } </script>

パターン4: 条件付きレンダリング(v-if/v-for)

用途: 状態に応じた動的な表示切り替え

<template> <div> <!-- 条件分岐 --> <v-alert v-if="status === 'success'" type="success">成功しました</v-alert> <v-alert v-else-if="status === 'error'" type="error">エラーが発生しました</v-alert> <v-alert v-else type="info">処理中...</v-alert> <!-- ループ表示 --> <v-list> <v-list-item v-for="(item, index) in items" :key="index"> {{ item.name }}: {{ item.value }} </v-list-item> </v-list> </div> </template> <script> export default { data() { return { status: 'pending', items: [] }; }, watch: { msg(newMsg) { this.status = newMsg.status; this.items = newMsg.payload || []; } } } </script>

パターン5: 外部ライブラリ(Chart.js)の使用

用途: Chart.jsを使ったカスタムグラフ

Inject
データ
→ template
Chart.js
<template> <canvas ref="chart"></canvas> </template> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> export default { data() { return { chart: null }; }, mounted() { this.initChart(); }, methods: { initChart() { const ctx = this.$refs.chart.getContext('2d'); this.chart = new Chart(ctx, { type: 'line', data: { labels: ['1月', '2月', '3月', '4月', '5月'], datasets: [{ label: 'データ', data: [12, 19, 3, 5, 2], borderColor: '#b92d5d' }] } }); } }, watch: { msg(newMsg) { if (this.chart && newMsg.payload) { this.chart.data.datasets[0].data = newMsg.payload; this.chart.update(); } } } } </script>

⚠️ Chart.js を ui-template で使う際の既知の不具合・落とし穴

Vue + Chart.js の組み合わせには、以下のような不具合報告があります。本格運用する前に必ず確認してください。

単純な時系列グラフであれば、ui-template + Chart.js より 標準の ui-chart(eCharts ベース) を使う方が、不具合リスク・実装コストともに少なく済みます。Chart.js は標準ノードでは表現できない要件がある場合に限って採用するのが安全です。

最新の不具合情報は Chart.js GitHub Issues および FlowFuse Dashboard Issues を参照してください。

🏋️ 8. 実践演習

📌 複数のフローを読み込むとき: このサイトの Dashboard 2.0 のフロー(サンプルフローと演習の解答例)は、すべて同じダッシュボード設定ノード(ui-base)を共有しています。2つ目以降のフローを読み込むと、「読み込もうとしているノードのいくつかは、既にワークスペース内に存在しています。」という通知が出ます。「コピーを読み込み」を選んでください。共有している設定ノードは既にあるものが使われ、どのフローのページも1つのダッシュボードにまとまります。ページはダッシュボードの左のメニューから選べます。ダッシュボード全体の見た目(ヘッダーやメニューの表示)は、最初に読み込んだフローの ui-base の設定になります。

ページが表示されないとき: ダッシュボードの設定ノード(ui-base)が2つ以上あると、そのうち1つのページしか表示されません。このサイトの以前の版のフローを読み込んでいると、この状態になります。以前の版のフローのタブを削除してから、エディタの メニュー → 設定ノード を開き、画面上部の「未使用」を選んで、どのノードからも使われていない ui-group・ui-page・ui-base・ui-theme を削除します。ui-group を消すとそれを使っていた ui-page が、ui-page を消すと ui-base が未使用になるので、未使用のものが無くなるまで繰り返してください。そのあとで、フローを読み込み直します。

演習1: シンプルなトグルスイッチ初級

📝 課題:

Vuetifyのv-switchを使って、ON/OFFを切り替えるカスタムウィジェットを作成してください。

💼 使いどころ: 標準のウィジェットでは足りない見た目の操作部品を、自分で用意する場面で使います。

🎯 要求仕様:

📊 期待される出力:

💡 ヒント

ui-templateの設定:

  • タイプ: ウィジェット (UI)
  • グループ: 任意のグループを選択または作成

Vue.jsのポイント:

  • v-modelでスイッチの状態をデータにバインド
  • @changeまたはwatchで状態変更を検知
  • this.send()でメッセージ送信

コード例:

<v-switch v-model="isOn" label="電源" @change="onChange" />
✅ 解答例フロー
[ { "id": "d2tpl_ex1_tab", "type": "tab", "label": "演習1: トグルスイッチ", "disabled": false, "info": "" }, { "id": "d2tpl_ex1_template", "type": "ui-template", "z": "d2tpl_ex1_tab", "group": "ex1_group", "page": "", "ui": "", "name": "トグルスイッチ", "order": 1, "width": 0, "height": 0, "format": "<template>\n <div class=\"toggle-widget\">\n <v-switch\n v-model=\"isOn\"\n :label=\"isOn ? 'ON' : 'OFF'\"\n color=\"primary\"\n @change=\"onChange\"\n />\n <p>現在の状態: <strong>{{ isOn ? '動作中' : '停止中' }}</strong></p>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n isOn: false\n };\n },\n methods: {\n onChange() {\n this.send({ payload: this.isOn });\n }\n },\n watch: {\n msg(newMsg) {\n if (typeof newMsg.payload === 'boolean') {\n this.isOn = newMsg.payload;\n }\n }\n }\n}\n</script>\n\n<style scoped>\n.toggle-widget {\n padding: 20px;\n text-align: center;\n}\n</style>", "passthru": true, "templateScope": "local", "className": "", "x": 200, "y": 100, "wires": [ [ "d2tpl_ex1_debug" ] ] }, { "id": "d2tpl_ex1_debug", "type": "debug", "z": "d2tpl_ex1_tab", "name": "出力確認", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "payload", "targetType": "msg", "statusVal": "payload", "statusType": "auto", "x": 410, "y": 100, "wires": [] }, { "id": "c2e1aa56f50f03bd", "type": "ui-base", "name": "Dashboard", "path": "/dashboard", "appIcon": "", "includeClientData": true, "acceptsClientConfig": ["ui-notification", "ui-control"], "showPathInSidebar": false, "headerContent": "page", "navigationStyle": "default", "titleBarStyle": "default", "showReconnectNotification": true, "notificationDisplayTime": 1, "showDisconnectNotification": true, "allowInstall": false }, { "id": "ex1_theme", "type": "ui-theme", "name": "Theme", "colors": { "surface": "#ffffff", "primary": "#b92d5d", "bgPage": "#eeeeee", "groupBg": "#ffffff", "groupOutline": "#cccccc" }, "sizes": { "pagePadding": "12px", "groupGap": "12px", "groupBorderRadius": "4px", "widgetGap": "12px", "density": "default" } }, { "id": "ex1_page", "type": "ui-page", "name": "演習ページ", "ui": "c2e1aa56f50f03bd", "path": "/exercise", "icon": "mdi-school", "layout": "grid", "theme": "ex1_theme", "breakpoints": [ {"name": "Default", "px": 0, "cols": 3}, {"name": "Tablet", "px": 576, "cols": 6}, {"name": "Desktop", "px": 1024, "cols": 12} ], "order": 1, "className": "", "visible": true, "disabled": false }, { "id": "ex1_group", "type": "ui-group", "name": "演習1", "page": "ex1_page", "width": "6", "height": "-1", "order": 1, "showTitle": true, "groupType": "default", "className": "", "visible": true, "disabled": false } ]

演習2: リアルタイムセンサー表示中級

📝 課題:

センサーデータ(温度・湿度)を受信して、カード形式でリアルタイム表示するウィジェットを作成してください。

💼 使いどころ: 届いた測定値を、複数の項目をまとめたカードとして即座に画面へ反映する場面で使います。

🎯 要求仕様:

📊 入力データ形式:

msg.payload = { "temperature": 25.5, "humidity": 60 }
💡 ヒント

Injectノードの設定:

  • msg.payload: JSON形式で温度・湿度を設定
  • 繰り返し: 5秒ごとに自動送信(テスト用)

Changeノードの設定: 送るたびに値を変えて試すため、Injectとui-templateの間に置きます。「値の代入」で msg.payload に「JSONata式」型の次の式を設定すると、温度(15〜35、小数1桁)と湿度(40〜80)が毎回変わります。

{"temperature": $round(15 + $random() * 20, 1), "humidity": $round(40 + $random() * 40)}

Vue.jsのポイント:

  • computedで温度に応じた色を計算
  • v-cardとv-iconでカード表示
  • watchでmsg変更を監視

Vuetifyアイコン例:

温度: mdi-thermometer 湿度: mdi-water-percent
✅ 解答例フロー
[ { "id": "d2tpl_ex2_tab", "type": "tab", "label": "演習2: センサー表示", "disabled": false, "info": "" }, { "id": "d2tpl_ex2_inject", "type": "inject", "z": "d2tpl_ex2_tab", "name": "センサーデータ", "props": [ { "p": "payload" } ], "repeat": "5", "crontab": "", "once": true, "onceDelay": 0.1, "topic": "", "payload": "{\"temperature\": 25.5, \"humidity\": 60}", "payloadType": "json", "x": 170, "y": 100, "wires": [ [ "ex2_change_random" ] ] }, { "id": "ex2_change_random", "type": "change", "z": "d2tpl_ex2_tab", "name": "ランダム値生成", "rules": [ { "t": "set", "p": "payload", "pt": "msg", "to": "{\"temperature\": $round(15 + $random() * 20, 1), \"humidity\": $round(40 + $random() * 40)}", "tot": "jsonata" } ], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 360, "y": 100, "wires": [["d2tpl_ex2_template"]] }, { "id": "d2tpl_ex2_template", "type": "ui-template", "z": "d2tpl_ex2_tab", "group": "ex2_group", "page": "", "ui": "", "name": "センサー表示", "order": 1, "width": 0, "height": 0, "format": "<template>\n <div class=\"sensor-dashboard\">\n <v-row>\n <v-col cols=\"6\">\n <v-card :color=\"tempColor\" dark>\n <v-card-title>\n <v-icon large left>mdi-thermometer</v-icon>\n 温度\n </v-card-title>\n <v-card-text class=\"sensor-value\">\n {{ temperature }}°C\n </v-card-text>\n </v-card>\n </v-col>\n <v-col cols=\"6\">\n <v-card color=\"blue\" dark>\n <v-card-title>\n <v-icon large left>mdi-water-percent</v-icon>\n 湿度\n </v-card-title>\n <v-card-text class=\"sensor-value\">\n {{ humidity }}%\n </v-card-text>\n </v-card>\n </v-col>\n </v-row>\n <p class=\"update-time\">最終更新: {{ lastUpdate }}</p>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n temperature: '--',\n humidity: '--',\n lastUpdate: '--'\n };\n },\n computed: {\n tempColor() {\n if (this.temperature === '--') return 'grey';\n if (this.temperature >= 30) return 'red';\n if (this.temperature <= 15) return 'blue';\n return 'green';\n }\n },\n watch: {\n msg(newMsg) {\n if (newMsg.payload) {\n this.temperature = newMsg.payload.temperature || '--';\n this.humidity = newMsg.payload.humidity || '--';\n this.lastUpdate = new Date().toLocaleTimeString('ja-JP');\n }\n }\n }\n}\n</script>\n\n<style scoped>\n.sensor-dashboard {\n padding: 10px;\n}\n.sensor-value {\n font-size: 36px;\n font-weight: bold;\n text-align: center;\n}\n.update-time {\n text-align: center;\n color: #666;\n margin-top: 15px;\n}\n</style>", "passthru": true, "templateScope": "local", "className": "", "x": 540, "y": 160, "wires": [ [] ] }, { "id": "c2e1aa56f50f03bd", "type": "ui-base", "name": "Dashboard", "path": "/dashboard", "appIcon": "", "includeClientData": true, "acceptsClientConfig": ["ui-notification", "ui-control"], "showPathInSidebar": false, "headerContent": "page", "navigationStyle": "default", "titleBarStyle": "default", "showReconnectNotification": true, "notificationDisplayTime": 1, "showDisconnectNotification": true, "allowInstall": false }, { "id": "ex2_theme", "type": "ui-theme", "name": "Theme", "colors": { "surface": "#ffffff", "primary": "#b92d5d", "bgPage": "#eeeeee", "groupBg": "#ffffff", "groupOutline": "#cccccc" }, "sizes": { "pagePadding": "12px", "groupGap": "12px", "groupBorderRadius": "4px", "widgetGap": "12px", "density": "default" } }, { "id": "ex2_page", "type": "ui-page", "name": "センサー", "ui": "c2e1aa56f50f03bd", "path": "/sensor", "icon": "mdi-gauge", "layout": "grid", "theme": "ex2_theme", "breakpoints": [ {"name": "Default", "px": 0, "cols": 3}, {"name": "Tablet", "px": 576, "cols": 6}, {"name": "Desktop", "px": 1024, "cols": 12} ], "order": 1, "className": "", "visible": true, "disabled": false }, { "id": "ex2_group", "type": "ui-group", "name": "センサーモニター", "page": "ex2_page", "width": "6", "height": "-1", "order": 1, "showTitle": true, "groupType": "default", "className": "", "visible": true, "disabled": false } ]

演習3: ToDoリスト中級

📝 課題:

タスクの追加・削除・完了切り替えができるToDoリストウィジェットを作成してください。

💼 使いどころ: 画面側で項目の追加や削除を行い、その結果をウィジェット内で保持する場面で使います。

🎯 要求仕様:

💡 ヒント

データ構造:

todos: [ { id: 1, text: "タスク1", done: false }, { id: 2, text: "タスク2", done: true } ]

Vue.jsのポイント:

  • v-forでリスト表示
  • v-checkboxで完了状態管理
  • 配列操作: push(追加)、filter(削除)
✅ 解答例フロー
[ { "id": "d2tpl_ex3_tab", "type": "tab", "label": "演習3: ToDoリスト", "disabled": false, "info": "" }, { "id": "d2tpl_ex3_template", "type": "ui-template", "z": "d2tpl_ex3_tab", "group": "ex3_group", "page": "", "ui": "", "name": "ToDoリスト", "order": 1, "width": 0, "height": 0, "format": "<template>\n <v-card class=\"todo-card\">\n <v-card-title>📝 ToDoリスト</v-card-title>\n <v-card-text>\n <v-text-field\n v-model=\"newTask\"\n label=\"新しいタスク\"\n append-icon=\"mdi-plus\"\n @click:append=\"addTask\"\n @keyup.enter=\"addTask\"\n />\n <v-list>\n <v-list-item v-for=\"todo in todos\" :key=\"todo.id\">\n <template v-slot:prepend>\n <v-checkbox\n v-model=\"todo.done\"\n @change=\"updateTodos\"\n hide-details\n />\n </template>\n <v-list-item-title :class=\"{ 'done': todo.done }\">\n {{ todo.text }}\n </v-list-item-title>\n <template v-slot:append>\n <v-btn icon=\"mdi-delete\" size=\"small\" @click=\"removeTask(todo.id)\" />\n </template>\n </v-list-item>\n </v-list>\n <p class=\"summary\">完了: {{ completedCount }} / {{ todos.length }}</p>\n </v-card-text>\n </v-card>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n newTask: '',\n todos: [],\n nextId: 1\n };\n },\n computed: {\n completedCount() {\n return this.todos.filter(t => t.done).length;\n }\n },\n methods: {\n addTask() {\n if (this.newTask.trim()) {\n this.todos.push({\n id: this.nextId++,\n text: this.newTask,\n done: false\n });\n this.newTask = '';\n this.updateTodos();\n }\n },\n removeTask(id) {\n this.todos = this.todos.filter(t => t.id !== id);\n this.updateTodos();\n },\n updateTodos() {\n this.send({ payload: this.todos });\n }\n },\n watch: {\n msg(newMsg) {\n if (Array.isArray(newMsg.payload)) {\n this.todos = newMsg.payload;\n this.nextId = Math.max(...this.todos.map(t => t.id), 0) + 1;\n }\n }\n }\n}\n</script>\n\n<style scoped>\n.todo-card {\n margin: 10px;\n}\n.done {\n text-decoration: line-through;\n color: #999;\n}\n.summary {\n text-align: center;\n margin-top: 15px;\n color: #666;\n}\n</style>", "passthru": true, "templateScope": "local", "className": "", "x": 200, "y": 100, "wires": [ [ "d2tpl_ex3_debug" ] ] }, { "id": "d2tpl_ex3_debug", "type": "debug", "z": "d2tpl_ex3_tab", "name": "ToDo出力", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "payload", "targetType": "msg", "x": 400, "y": 100, "wires": [] }, { "id": "c2e1aa56f50f03bd", "type": "ui-base", "name": "Dashboard", "path": "/dashboard", "appIcon": "", "includeClientData": true, "acceptsClientConfig": ["ui-notification", "ui-control"], "showPathInSidebar": false, "headerContent": "page", "navigationStyle": "default", "titleBarStyle": "default", "showReconnectNotification": true, "notificationDisplayTime": 1, "showDisconnectNotification": true, "allowInstall": false }, { "id": "ex3_theme", "type": "ui-theme", "name": "Theme", "colors": { "surface": "#ffffff", "primary": "#b92d5d", "bgPage": "#eeeeee", "groupBg": "#ffffff", "groupOutline": "#cccccc" }, "sizes": { "pagePadding": "12px", "groupGap": "12px", "groupBorderRadius": "4px", "widgetGap": "12px", "density": "default" } }, { "id": "ex3_page", "type": "ui-page", "name": "ToDo", "ui": "c2e1aa56f50f03bd", "path": "/todo", "icon": "mdi-checkbox-marked", "layout": "grid", "theme": "ex3_theme", "breakpoints": [ {"name": "Default", "px": 0, "cols": 3}, {"name": "Tablet", "px": 576, "cols": 6}, {"name": "Desktop", "px": 1024, "cols": 12} ], "order": 1, "className": "", "visible": true, "disabled": false }, { "id": "ex3_group", "type": "ui-group", "name": "ToDo", "page": "ex3_page", "width": "6", "height": "-1", "order": 1, "showTitle": true, "groupType": "default", "className": "", "visible": true, "disabled": false } ]

演習4: インタラクティブダッシュボード上級

📝 課題:

複数のデバイスの状態を表示し、各デバイスの制御ができるダッシュボードを作成してください。

💼 使いどころ: 複数台の機器の状態表示と操作を1つの画面にまとめる場面で使います。

🎯 要求仕様:

💡 ヒント

データ構造:

devices: [ { id: 'light', name: '照明', icon: 'mdi-lightbulb', on: false }, { id: 'aircon', name: 'エアコン', icon: 'mdi-air-conditioner', on: false }, { id: 'fan', name: '換気扇', icon: 'mdi-fan', on: false } ]

送信データ形式:

msg.payload = { device: 'light', command: 'on' // または 'off' }
✅ 解答例フロー
[ { "id": "d2tpl_ex4_tab", "type": "tab", "label": "演習4: デバイス制御", "disabled": false, "info": "" }, { "id": "d2tpl_ex4_template", "type": "ui-template", "z": "d2tpl_ex4_tab", "group": "ex4_group", "page": "", "ui": "", "name": "デバイス制御パネル", "order": 1, "width": 0, "height": 0, "format": "<template>\n <div class=\"device-panel\">\n <h2>🏠 スマートホーム制御</h2>\n <v-row>\n <v-col v-for=\"device in devices\" :key=\"device.id\" cols=\"4\">\n <v-card \n :color=\"device.on ? 'primary' : 'grey-lighten-2'\"\n :dark=\"device.on\"\n class=\"device-card\"\n @click=\"toggleDevice(device)\"\n >\n <v-card-text class=\"text-center\">\n <v-icon size=\"64\" :class=\"{ 'rotating': device.id === 'fan' && device.on }\">\n {{ device.icon }}\n </v-icon>\n <h3>{{ device.name }}</h3>\n <v-chip :color=\"device.on ? 'green' : 'red'\" small>\n {{ device.on ? 'ON' : 'OFF' }}\n </v-chip>\n </v-card-text>\n </v-card>\n </v-col>\n </v-row>\n <v-divider class=\"my-4\" />\n <div class=\"action-buttons\">\n <v-btn color=\"success\" @click=\"allOn\">全てON</v-btn>\n <v-btn color=\"error\" @click=\"allOff\">全てOFF</v-btn>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n devices: [\n { id: 'light', name: '照明', icon: 'mdi-lightbulb', on: false },\n { id: 'aircon', name: 'エアコン', icon: 'mdi-air-conditioner', on: false },\n { id: 'fan', name: '換気扇', icon: 'mdi-fan', on: false }\n ]\n };\n },\n methods: {\n toggleDevice(device) {\n device.on = !device.on;\n this.sendCommand(device.id, device.on ? 'on' : 'off');\n },\n allOn() {\n this.devices.forEach(d => {\n d.on = true;\n this.sendCommand(d.id, 'on');\n });\n },\n allOff() {\n this.devices.forEach(d => {\n d.on = false;\n this.sendCommand(d.id, 'off');\n });\n },\n sendCommand(deviceId, command) {\n this.send({\n payload: {\n device: deviceId,\n command: command\n },\n topic: 'device_control'\n });\n }\n },\n watch: {\n msg(newMsg) {\n if (newMsg.payload && newMsg.payload.device) {\n const device = this.devices.find(d => d.id === newMsg.payload.device);\n if (device) {\n device.on = newMsg.payload.command === 'on';\n }\n }\n }\n }\n}\n</script>\n\n<style scoped>\n.device-panel {\n padding: 20px;\n}\n.device-card {\n cursor: pointer;\n transition: transform 0.2s;\n}\n.device-card:hover {\n transform: scale(1.05);\n}\n.rotating {\n animation: spin 2s linear infinite;\n}\n@keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n}\n.action-buttons {\n display: flex;\n gap: 10px;\n justify-content: center;\n}\n</style>", "passthru": true, "templateScope": "local", "className": "", "x": 220, "y": 100, "wires": [ [ "d2tpl_ex4_debug" ] ] }, { "id": "d2tpl_ex4_debug", "type": "debug", "z": "d2tpl_ex4_tab", "name": "制御コマンド", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "payload", "targetType": "msg", "statusVal": "payload.device", "statusType": "auto", "x": 450, "y": 100, "wires": [] }, { "id": "c2e1aa56f50f03bd", "type": "ui-base", "name": "Dashboard", "path": "/dashboard", "appIcon": "", "includeClientData": true, "acceptsClientConfig": ["ui-notification", "ui-control"], "showPathInSidebar": false, "headerContent": "page", "navigationStyle": "default", "titleBarStyle": "default", "showReconnectNotification": true, "notificationDisplayTime": 1, "showDisconnectNotification": true, "allowInstall": false }, { "id": "ex4_theme", "type": "ui-theme", "name": "Theme", "colors": { "surface": "#ffffff", "primary": "#b92d5d", "bgPage": "#eeeeee", "groupBg": "#ffffff", "groupOutline": "#cccccc" }, "sizes": { "pagePadding": "12px", "groupGap": "12px", "groupBorderRadius": "4px", "widgetGap": "12px", "density": "default" } }, { "id": "ex4_page", "type": "ui-page", "name": "スマートホーム", "ui": "c2e1aa56f50f03bd", "path": "/smart-home", "icon": "mdi-home-automation", "layout": "grid", "theme": "ex4_theme", "breakpoints": [ {"name": "Default", "px": 0, "cols": 3}, {"name": "Tablet", "px": 576, "cols": 6}, {"name": "Desktop", "px": 1024, "cols": 12} ], "order": 1, "className": "", "visible": true, "disabled": false }, { "id": "ex4_group", "type": "ui-group", "name": "デバイス制御", "page": "ex4_page", "width": "6", "height": "-1", "order": 1, "showTitle": true, "groupType": "default", "className": "", "visible": true, "disabled": false } ]

🎓 9. まとめ

templateの重要ポイント

⚠️ よくある間違い

🔧 10. トラブルシューティング

よくある問題と解決方法

問題 原因 解決方法
ウィジェットが表示されない Group未設定またはエラー Groupを設定し、ブラウザのコンソールでエラー確認
メッセージが受信できない watch設定ミスまたはプロパティ名誤り watch: { msg(newMsg) {...} }の形式を確認
send()が動作しない thisの参照が失われている アロー関数を使用するか、外側でconst self = thisを保存
CSSが適用されない scopedの影響または優先度不足 !importantを追加またはscopedを外す
Vuetifyコンポーネントが動かない v-model設定ミスまたはデータ未定義 data()でv-modelに対応する変数を定義
ページリロードで状態がリセット 状態がブラウザ内のみ resendOnRefresh: trueを設定しNode-REDから再送信
Chart.js でクラッシュ/無限ループ/拡大時にリサイズしない Vue リアクティブとの相性、chart instance の管理ミス 「7. 実用的な使用パターン」内のパターン5 末尾の警告ボックスを参照

💡 11. 実務での活用例

ケース1: カスタムセンサーダッシュボード

複数センサーからのデータ受信 ↓ ui-template(グラフ表示) - Chart.jsでリアルタイムグラフ - 閾値超過時に色変更 - 履歴データの表示切替 ↓ アラート表示 + データベース保存

ケース2: 設備制御パネル

ui-template(制御パネル) - 設備一覧をカード形式で表示 - 状態に応じたアイコン・色 - 制御ボタン(起動/停止/緊急停止) ↓ MQTT送信 → PLC/デバイス制御

ケース3: ファイルアップロードシステム

ui-template(ファイルアップロード) - v-file-inputでファイル選択 - プログレスバーで進捗表示 - ファイル情報のプレビュー ↓ Change(保存先のファイル名を msg.filename に設定) ↓ Write File → ストレージ保存(Buffer のまま書き込める)

ケース4: カスタムレポート画面

データベースクエリ ↓ ui-template(レポート表示) - v-data-tableで高度なテーブル - ソート・フィルター・ページネーション - CSVエクスポートボタン ↓ PDF生成 or メール送信

📚 12. 追加リソース


このガイドが役に立ちましたら、実際のプロジェクトで練習してみてください!
templateはDashboard 2.0の最も強力なウィジェットです。

参照元:FlowFuse Dashboard 2.0 公式ドキュメント

🏠