温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

d3.js怎么在Vue项目中使用

发布时间:2021-03-10 17:15:59 来源:亿速云 阅读:640 作者:Leah 栏目:web开发

这期内容当中小编将会给大家带来有关d3.js怎么在Vue项目中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

首先安装

npm install d3 --save-dev

以防万一,然后看package.json

d3.js怎么在Vue项目中使用

安装完成

在我们开始之前,让我们渲染一个Vue组件,它使用常规的D3 DOM操作呈现一个简单的折线图:

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

代码简单易懂,但这仅仅是一个基本的例子。因为我们没有使用模板,所以需要更多操作和计算的更复杂的可视化会掩盖组件的设计和逻辑。上述方法的另一个警告是,我们不能使用scopedCSS 的属性,因为D3会动态地向DOM添加元素。

d3.js怎么在Vue项目中使用

可以使用比较奇怪,但是代码比较优雅的方式去实现

<template>
 <svg width="500" height="270">
  <g >
   <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>

上述就是小编为大家分享的d3.js怎么在Vue项目中使用了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI