在 Vue3 中使用 LogicFlow 更新节点名称

在 Vue3 中更新 LogicFlow 节点名称有多种方式,下面我为你详细介绍几种常用方法。

🔧 核心更新方法

1. 使用 updateText方法(推荐)

这是最直接的方式,通过节点 ID 更新文本内容:

xml 复制代码
<template>
  <div>
    <div ref="container" style="width: 100%; height: 500px;"></div>
    <button @click="updateNodeName">更新节点名称</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import LogicFlow from '@logicflow/core';
import '@logicflow/core/dist/style/index.css';

const container = ref(null);
const lf = ref(null);
const selectedNodeId = ref('');

onMounted(() => {
  lf.value = new LogicFlow({
    container: container.value,
    grid: true,
  });

  // 示例数据
  lf.value.render({
    nodes: [
      {
        id: 'node_1',
        type: 'rect',
        x: 100,
        y: 100,
        text: '原始名称'
      }
    ]
  });

  // 监听节点点击,获取选中节点ID
  lf.value.on('node:click', ({ data }) => {
    selectedNodeId.value = data.id;
  });
});

// 更新节点名称
const updateNodeName = () => {
  if (!selectedNodeId.value) {
    alert('请先点击选择一个节点');
    return;
  }

  const newName = prompt('请输入新的节点名称', '新名称');
  if (newName) {
    // 使用 updateText 方法更新节点文本
    lf.value.updateText(selectedNodeId.value, newName);
  }
};
</script>

2. 通过 setProperties方法更新

这种方法可以同时更新文本和其他属性:

ini 复制代码
// 更新节点属性,包括名称
const updateNodeWithProperties = () => {
  if (!selectedNodeId.value) return;

  const newNodeName = '更新后的节点名称';
  
  // 获取节点当前属性
  const nodeModel = lf.value.getNodeModelById(selectedNodeId.value);
  const currentProperties = nodeModel.properties || {};
  
  // 更新属性
  lf.value.setProperties(selectedNodeId.value, {
    ...currentProperties,
    nodeName: newNodeName,
    updatedAt: new Date().toISOString()
  });
  
  // 同时更新显示文本
  lf.value.updateText(selectedNodeId.value, newNodeName);
};

🎯 事件监听与交互方式

1. 双击编辑模式

实现双击节点直接进入编辑模式:

ini 复制代码
// 监听双击事件
lf.value.on('node:dblclick', ({ data }) => {
  const currentNode = lf.value.getNodeModelById(data.id);
  const currentText = currentNode.text?.value || '';
  
  const newText = prompt('编辑节点名称:', currentText);
  if (newText !== null) {
    lf.value.updateText(data.id, newText);
  }
});

2. 右键菜单编辑

结合 Menu 插件实现右键菜单编辑:

javascript 复制代码
import { Menu } from '@logicflow/extension';
import '@logicflow/extension/lib/style/index.css';

// 初始化时注册菜单插件
lf.value = new LogicFlow({
  container: container.value,
  plugins: [Menu],
});

// 配置右键菜单
lf.value.extension.menu.setMenuConfig({
  nodeMenu: [
    {
      text: '编辑名称',
      callback: (node) => {
        const currentText = node.text || '';
        const newText = prompt('编辑节点名称:', currentText);
        if (newText) {
          lf.value.updateText(node.id, newText);
        }
      }
    },
    {
      text: '删除',
      callback: (node) => {
        lf.value.deleteNode(node.id);
      }
    }
  ]
});

💡 自定义节点名称编辑

对于自定义节点,可以重写文本相关方法:

kotlin 复制代码
import { RectNode, RectNodeModel } from '@logicflow/core';

class CustomNodeModel extends RectNodeModel {
  // 自定义文本样式
  getTextStyle() {
    const style = super.getTextStyle();
    return {
      ...style,
      fontSize: 14,
      fontWeight: 'bold',
      fill: '#1e40af',
    };
  }
  
  // 初始化节点数据
  initNodeData(data) {
    super.initNodeData(data);
    // 确保文本格式正确
    this.text = {
      x: data.x,
      y: data.y + this.height / 2 + 10,
      value: data.text || '默认节点'
    };
  }
}

// 注册自定义节点
lf.value.register({
  type: 'custom-node',
  view: RectNode,
  model: CustomNodeModel
});

🚀 批量更新与高级功能

1. 批量更新多个节点

ini 复制代码
// 批量更新所有节点名称
const batchUpdateNodeNames = () => {
  const graphData = lf.value.getGraphData();
  const updatedNodes = graphData.nodes.map(node => ({
    ...node,
    text: `${node.text}(已更新)`
  }));
  
  // 重新渲染
  lf.value.render({
    nodes: updatedNodes,
    edges: graphData.edges
  });
};

// 按条件更新节点
const updateNodesByCondition = () => {
  const graphData = lf.value.getGraphData();
  const updatedNodes = graphData.nodes.map(node => {
    if (node.type === 'rect') {
      return {
        ...node,
        text: `矩形节点-${node.id}`
      };
    }
    return node;
  });
  
  lf.value.render({
    nodes: updatedNodes,
    edges: graphData.edges
  });
};

2. 实时保存与撤销重做

javascript 复制代码
// 监听文本变化并自动保存
lf.value.on('node:text-update', ({ data }) => {
  console.log('节点文本已更新:', data);
  saveToBackend(lf.value.getGraphData());
});

// 实现撤销重做功能
const undo = () => {
  lf.value.undo();
};

const redo = () => {
  lf.value.redo();
};

// 启用历史记录
lf.value = new LogicFlow({
  container: container.value,
  grid: true,
  history: true, // 启用历史记录
  historySize: 100 // 设置历史记录大小
});

⚠️ 注意事项与最佳实践

  1. 文本对象格式 :LogicFlow 中文本可以是字符串或对象格式 {value: '文本', x: 100, y: 100}
  2. 更新时机 :确保在 lf.render()之后再进行更新操作
  3. 错误处理:更新前检查节点是否存在
  4. 性能优化:批量更新时考虑使用防抖
javascript 复制代码
// 安全的更新函数
const safeUpdateNodeName = (nodeId, newName) => {
  if (!lf.value) {
    console.error('LogicFlow 实例未初始化');
    return false;
  }
  
  const nodeModel = lf.value.getNodeModelById(nodeId);
  if (!nodeModel) {
    console.error(`节点 ${nodeId} 不存在`);
    return false;
  }
  
  try {
    lf.value.updateText(nodeId, newName);
    return true;
  } catch (error) {
    console.error('更新节点名称失败:', error);
    return false;
  }
};

这些方法涵盖了 Vue3 中 LogicFlow 节点名称更新的主要场景,你可以根据具体需求选择合适的方式。

相关推荐
天若有情6739 分钟前
【C++原创开源】formort.h:一行头文件,实现比JS模板字符串更爽的链式拼接+响应式变量
开发语言·javascript·c++·git·github·开源项目·模版字符串
天***885213 分钟前
Edge 浏览器离线绿色增强版+官方安装包,支持win7等系统
前端·edge
漫游的渔夫22 分钟前
别再直接 `json.loads` 了!AI 返回的 JSON 坑位指南
前端·人工智能
软件工程师文艺33 分钟前
从0到1:Claude Code如何用React构建CLI应用
前端·react.js·前端框架
M ? A43 分钟前
Vue 迁移 React 实战:VuReact 一键自动化转换方案
前端·vue.js·经验分享·react.js·开源·自动化·vureact
yuki_uix44 分钟前
重排、重绘与合成——浏览器渲染性能的底层逻辑
前端·javascript·面试
Burt1 小时前
我的 2026 全栈选型:Vue3 + Elysia + Bun + AlovaJS
vue.js·全栈·bun
止观止1 小时前
拥抱 ESNext:从 TC39 提案到生产环境中的现代 JS
开发语言·javascript·ecmascript·esnext
沃尔威武1 小时前
调试黑科技:Chrome DevTools时间旅行调试实战
前端·科技·chrome devtools
小锋java12341 小时前
SpringBoot 4 + Spring Security 7 + Vue3 前后端分离项目设计最佳实践
java·vue.js·spring boot