d3.js在vue项目中的安装及案例

1. 首先安装

npm install d3 --save-dev或者
cnpm install d3 --save-dev  (需要先安装cnpm,本人喜欢用这个国内镜像比较快)

以防万一,然后看package.json

2. 引入:main.js

import * as d3 from "d3";

Vue.prototype.$d3 = d3;
window.d3 = d3;   //暂时设置为全局变量

3. demo代码:  demo源码参考地址

<template>
    <div style="width: 100%;height: 100%;">
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"
         width="960" height="500"> </svg>
    </div>
</template>
<script>
    export default {
        mounted() {
            var svg = d3.select("svg"),
                width = +svg.attr("width"),
                height = +svg.attr("height"),
                color = d3.scaleOrdinal(d3.schemeCategory10);

            var a = {
                    id: "a"
                },
                b = {
                    id: "b"
                },
                c = {
                    id: "c"
                },
                nodes = [a, b, c],
                links = [];

            var simulation = d3.forceSimulation(nodes)
                .force("charge", d3.forceManyBody().strength(-1000))
                .force("link", d3.forceLink(links).distance(200))
                .force("x", d3.forceX())
                .force("y", d3.forceY())
                .alphaTarget(1)
                .on("tick", ticked);

            var g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"),
                link = g.append("g").attr("stroke", "#000").attr("stroke-width", 1.5).selectAll(".link"),
                node = g.append("g").attr("stroke", "#fff").attr("stroke-width", 1.5).selectAll(".node");

            restart();

            d3.timeout(function() {
                links.push({
                    source: a,
                    target: b
                }); // Add a-b.
                links.push({
                    source: b,
                    target: c
                }); // Add b-c.
                links.push({
                    source: c,
                    target: a
                }); // Add c-a.
                restart();
            }, 1000);

            d3.interval(function() {
                nodes.pop(); // Remove c.
                links.pop(); // Remove c-a.
                links.pop(); // Remove b-c.
                restart();
            }, 2000, d3.now());

            d3.interval(function() {
                nodes.push(c); // Re-add c.
                links.push({
                    source: b,
                    target: c
                }); // Re-add b-c.
                links.push({
                    source: c,
                    target: a
                }); // Re-add c-a.
                restart();
            }, 2000, d3.now() + 1000);

            function restart() {

                // Apply the general update pattern to the nodes.
                node = node.data(nodes, function(d) {
                    return d.id;
                });

                node.exit().transition()
                    .attr("r", 0)
                    .remove();

                node = node.enter().append("circle")
                    .attr("fill", function(d) {
                        return color(d.id);
                    })
                    .call(function(node) {
                        node.transition().attr("r", 8);
                    })
                    .merge(node);

                // Apply the general update pattern to the links.
                link = link.data(links, function(d) {
                    return d.source.id + "-" + d.target.id;
                });

                // Keep the exiting links connected to the moving remaining nodes.
                link.exit().transition()
                    .attr("stroke-opacity", 0)
                    .attrTween("x1", function(d) {
                        return function() {
                            return d.source.x;
                        };
                    })
                    .attrTween("x2", function(d) {
                        return function() {
                            return d.target.x;
                        };
                    })
                    .attrTween("y1", function(d) {
                        return function() {
                            return d.source.y;
                        };
                    })
                    .attrTween("y2", function(d) {
                        return function() {
                            return d.target.y;
                        };
                    })
                    .remove();

                link = link.enter().append("line")
                    .call(function(link) {
                        link.transition().attr("stroke-opacity", 1);
                    })
                    .merge(link);

                // Update and restart the simulation.
                simulation.nodes(nodes);
                simulation.force("link").links(links);
                simulation.alpha(1).restart();
            }

            function ticked() {
                node.attr("cx", function(d) {
                        return d.x;
                    })
                    .attr("cy", function(d) {
                        return d.y;
                    })

                link.attr("x1", function(d) {
                        return d.source.x;
                    })
                    .attr("y1", function(d) {
                        return d.source.y;
                    })
                    .attr("x2", function(d) {
                        return d.target.x;
                    })
                    .attr("y2", function(d) {
                        return d.target.y;
                    });
            }
        },
    }
</script>

4. demo效果图

案例2:  渲染一个Vue组件,它使用常规的D3 DOM操作呈现一个简单的折线图:

<template>
  <svg width="500" height="270">
    <g style="transform: translate(0, 10px)">
      <path :d="line" />
    </g>
  </svg>
</template>
<script>
import * as d3 from ‘d3‘;
export default {
  name: ‘vue-line-chart‘,
  data() {
    return {
      data: [99, 71, 78, 25, 36, 92],
      line: ‘‘,
    };
  },
  mounted() {
    this.calculatePath();
  },
  methods: {
    getScales() {
      const x = d3.scaleTime().range([0, 430]);
      const y = d3.scaleLinear().range([210, 0]);
      d3.axisLeft().scale(x);
      d3.axisBottom().scale(y);
      x.domain(d3.extent(this.data, (d, i) => i));
      y.domain([0, d3.max(this.data, d => d)]);
      return { x, y };
    },
    calculatePath() {
      const scale = this.getScales();
      const path = d3.line()
        .x((d, i) => scale.x(i))
        .y(d => scale.y(d));
      this.line = path(this.data);
    },
  },
};
</script>
<style lang="sass" scoped>
svg
  margin: 25px;
path
  fill: none
  stroke: #76BF8A
  stroke-width: 3px
</style>

非常酷,即使它没有公开任何属性并且数据是硬编码的,它很好地将视图从逻辑中分离出来,并且使用Vue钩子,方法和data对象,现象和上图一样的

原文地址:https://www.cnblogs.com/sea520/p/11875164.html

时间: 2024-08-06 15:55:47

d3.js在vue项目中的安装及案例的相关文章

cytoscape.js在vue项目中的安装及案例

1. 安装: npm i cytoscape --save 2. 引入:main.js import cytoscape from 'cytoscape'; Vue.prototype.$cytoscape = cytoscape; 3. demo代码: <template> <div id="MainCy" style="width: 100%;height: 100%;"></div> </template> &l

在vue项目中的axios使用配置记录

默认vue项目中已经安装axios,基于element-ui开发,主要记录配置的相关. axiosConfig.js import Vue from 'vue' import axios from 'axios' import qs from 'qs' import { Message, Loading } from 'element-ui' // 响应时间 axios.defaults.timeout = 5 * 1000 // 配置cookie // axios.defaults.withC

前端框架Vue.js——vue-i18n ,vue项目中如何实现国际化

每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code 一.前言 趁着10月的最后一天,来写一篇关于前端国际化的实践型博客.国际化应该都不陌生,就是一个网站.应用可以实现语言的切换. 在这就不谈原理,只说说如何实现中英文的切换.做技术的总得先把 demo 做出来嘛. 二.demo 场景需求分析 需求很简单,左上角 ''网易云音乐''就是一个中英文切换的按钮,点击弹出提示框,确认切换语言后,实现英文版本. 切换成英文版本: 三.实现国际化

在vue项目中使用canvas-nest.js,报parameter 1 is not of type &#39;Element&#39;

canvas-nest.js是一款轻量的网页特效,如图: github地址:https://github.com/hustcc/canvas-nest.js 在普通的html项目中,只要将<script src="dist/canvas-nest.js"></script>插入到body标签最下边即可. 在vue项目中,使用时配置 1 import CanvasNest from 'canvas-nest.js'; 2 3 const config = { //

Vue 项目中使用 jsPlumb

jsPlumb 介绍 jsPlumb 是一个强大的 JavaScript 连线库,它可以将 html中 的元素用箭头.曲线.直线等连接起来,适用于开发 Web 上的图表.建模工具.流程图.关系图等. jsPlumb 参考网站 博客园:http://www.cnblogs.com/leomYili/p/6346526.html?utm_source=itdadao&utm_medium=referral 官网:https://www.jsplumbtoolkit.com/ 安装 jsPlumb v

如何在Vue项目中使用vw实现移动端适配

https://www.w3cplus.com/mobile/vw-layout-in-vue.html  原文网址 如何在Vue项目中使用vw实现移动端适配 作者:大漠 日期:2018-01-25 点击:10362 vw Layout 布局 Vue mobile 编辑推荐:使用 Coding.net 搭建静态博客,自定义域名,全站 HTTPS 加密,自动实时部署, 立即托管您的网站! 有关于移动端的适配布局一直以来都是众说纷纭,对应的解决方案也是有很多种.在<使用Flexible实现手淘H5页

转:如何在Vue项目中使用vw实现移动端适配

https://www.w3cplus.com/mobile/vw-layout-in-vue.html 有关于移动端的适配布局一直以来都是众说纷纭,对应的解决方案也是有很多种.在<使用Flexible实现手淘H5页面的终端适配>提出了Flexible的布局方案,随着viewport单位越来越受到众多浏览器的支持,因此在<再聊移动端页面的适配>一文中提出了vw来做移动端的适配问题.到目前为止不管是哪一种方案,都还存在一定的缺陷.言外之意,还没有哪一个方案是完美的. 事实上真的不完美

Vue项目中遇到的一些问题总结

一.开发环境使用Ajax请求,报错 网上查的资料,在config中的index.js这样设置 proxyTable:{ '/api':{ target:'', //此处为你的API接口地址 changeOrigin:true, pathRewrite:{ '^/api':'' //这里理解为用api代替target中的地址 } } } 配置完后,请求依然报错,大致是https证书的问题 [HPM] Error occured while trying to proxy request /xxx/

如何在Vue项目中使用Typescript

0.前言 本快速入门指南将会教你如何在Vue项目中使用TypeScript进行开发.本指南非常灵活,它可以将TypeScript集成到现有的Vue项目中任何一个阶段. 1.初始化项目 首先,创建一个新的项目目录. mkdir typescript-vue-tutorial cd typescript-vue-tutorial 接着,在目录中创建如下目录结构. typescript-vue-tutorial/ ├─ dist/ └─ src/ └─ components/ TypeScript文件