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) }