在 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 节点名称更新的主要场景,你可以根据具体需求选择合适的方式。

相关推荐
子兮曰2 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖2 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神2 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛4 小时前
Nginx日志切分
服务器·前端·nginx
Daniel李华4 小时前
echarts使用案例
android·javascript·echarts
北原_春希4 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS4 小时前
echarts天气折线图
javascript·vue.js·echarts
尽意啊4 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜4 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive4 小时前
Vue3使用ECharts
前端·javascript·echarts