vue+ D3+drag


import template from './explore.vue' //import dataJson from './data.json' import * as d3 from 'd3' import Draggabilly from 'draggabilly' export default { ...template, name: 'explore', data(){ return { dataJson: { "name":"中国", "children": [{ "name":"广西" , "children": [ { "name":"桂林", "children": [ {"name":"秀峰区"}, {"name":"叠彩区"}, {"name":"象山区"}, {"name":"七星区", "children": [ {"name":"哈尔滨"}, {"name":"齐齐哈尔"}, {"name":"牡丹江"}, {"name":"大庆"} ] } ] }, {"name":"南宁"}, {"name":"柳州"}, {"name":"防城港"} ] }] } } }, mounted () { this.$nextTick(function () { let width = 600 let height = 600 let svg = d3.select('#tree-container').append('svg') .attr('width', 1500) .attr('height', 850) .append('g') .attr('transform', 'translate(40,0)') /* 定义了元素拖拽行为的原点 设置为圆的圆心位置可以避免明显的元素跳动 第一个参考连接中的例子可以看到明显的跳动 */ var drag = d3.drag() .subject(function() { var t = d3.select(this); return { x: t.attr("cx"), y: t.attr("cy") }; }) .on("drag", dragmove); /* 树状图 * */ let cluster = d3.tree() .size([width, height - 100]); // 此处省略请求方法 let nodes = d3.hierarchy(this.dataJson); let haveDeal = cluster(nodes); /** * 所有节点 * */ let lastAfterEdit = haveDeal.descendants(); /** * 所有连线 * */ let links = nodes.links(); /** * 画连线(垂直图用d3.linkVertical() x return d.x y return d.y) * */ let link = svg.selectAll('.link') .data(links) .enter() .append("path") .attr("class", "link") .attr("d", d3.linkHorizontal() .x(function (d) { return d.y; }) .y(function (d) { return d.x; })); /** * 画圆圈(垂直图 cx return d.x /cy return d.y) * */ var circles = svg.selectAll('.circle') .data(lastAfterEdit) .enter() .append("circle") .attr('cx', function (d) { return d.y; }) .attr('cy', function (d) { return d.x; }) .attr("r", 6) .attr('class','nodes-group') .attr("data", function (d) { return d.data.name; }) .call(drag); /** * 画文本(垂直图 x return d.x /y return d.y) * */ var texts = svg .selectAll('text') .data(lastAfterEdit) .enter() .append('text') .attr('x', function (d) { return d.y; }) .attr("id", function (d) { return d.data.name; }) .attr('y', function (d) { return d.x; }) .text(function (d) { return d.data.name; }) .style("text-anchor", function (d) { return d.children ? "end" : "start"; }) .attr("dx", function (d) { return d.children ? -10 : 10; }) .attr('dy', function (d) { return 5; }); function dragmove(d) { /* 只能拖拽圆 */ d3.select(this) .attr("cx", function() { return d.cx = d3.event.x }) .attr("cy", d.cy = d3.event.y) /* 拖拽圆后,要控制文字的上(减)、下(加)、左(减)、右方向 */ var txt = svg.select('#'+d.data.name) .attr('y',function(){ return d.y = event.offsetY }) .attr('x',function(){ return d.x = event.offsetX-40 }) /* 重新绘制线的路径 (x/y 同理)*/ link.attr("d", d3.linkHorizontal() .x(function (d) { return d.y; }) .y(function (d) { return d.x; })); } }) } } if (typeof window !== 'undefined' && window.Vue) { window.Vue.component('o-explore', template) }

  

原文地址:https://www.cnblogs.com/caolidan/p/8993869.html