vue 构建根组件

Sparklines can be used to quickly visualize data variance. They are small and intuitive to understand.

迷你图可用于快速可视化数据差异。 它们很小且易于理解。

We’ll be using Vue and D3 to build a small sparkline component using Vue.js. In an upcoming article, I’ll show you how to use this component to build a “dashboard” for easy visualization of many data points.

我们将使用Vue公司和D3建立一个小型的迷你图使用分量Vue.js 。 在下一篇文章中,我将向您展示如何使用此组件来构建“仪表板”,以轻松可视化许多数据点。

First, make sure you have the Vue CLI installed. Then, create a new project.

首先,请确保您已安装Vue CLI 。 然后,创建一个新项目。

vue create sparkboard

The CLI will ask you questions about how you’d like to set up your project. You can accept the defaults or manually select features you like. I manually selected…

CLI将询问您有关如何设置项目的问题。 您可以接受默认设置,也可以手动选择所需的功能。 我手动选择了…

  • Babel巴别塔
  • Linter/Formatter短绒/格式化
  • ESLint + PrettierESLint +漂亮
  • Lint on save保存时不掉毛
  • In dedicated config files在专用配置文件中

Once the project has been created, start the dev server.

创建项目后,启动开发服务器。

cd sparkboardnpm run serve

Create a new component in the src/components directory called SparkLine.vue

src/components目录中创建一个名为SparkLine.vue的新组件。

<template>  <svg viewBox="0 0 200 40">    <path d="M 0 20 H 200"          fill="none"          stroke-width="3"          stroke-color="gold" />  </svg></template><script>export default {  name: "SparkLine"}</script>

Notice the root element of the component is an <svg>. This is the element we’ll bind D3 to when creating the chart. You can also see that the <svg> has a viewBox of 0 0 200 40. This gives it the dimensions of 200 pixels wide by 40 pixels tall. The actual width and height are determined by the element’s container, but the 200 x 40 viewBox gives it a good height to width ratio for a sparkline chart.

注意,组件的根元素是<svg> 。 这是我们在创建图表时将D3绑定到的元素。 您还可以看到<svg>viewBox0 0 200 40 。 这使其尺寸为200像素宽乘以40像素高。 实际的宽度和高度由元素的容器确定,但200 x 40的viewBoxviewBox提供了良好的高度与宽度之比。

Finally, there is a <path> inside the <svg>. This is our actual line. For right now, it’s just a hard-coded, perfectly straight, horizontal line.

最后,在<svg>内有一个<path> <svg> 。 这是我们的实际路线。 目前,这只是一条硬编码的,完美的直线,水平线。

We can see our progress so far by putting our component in the main App.vue. In that file, replace everything in the template with…

通过将组件放在主App.vue中,我们可以看到到目前为止的进展。 在该文件中,将模板中的所有内容替换为...

<template>  <div style="width: 100px">    <SparkLine />  </div></template>

Notice how we put the sparkline component inside a container element with a narrow width. This will give it the traditional small appearance.

注意,我们如何将迷你图组件放置在宽度较窄的容器元素内。 这将使其具有传统的外观。

Now, replace the script section with…

现在,将脚本部分替换为...

<script>import SparkLine from "./components/SparkLine.vue";export default {  name: "App",  components: {    SparkLine  }};</script>

You may notice how we just changed HelloWorld to SparkLine. Everything else is the same.

您可能会注意到我们如何将HelloWorld更改为SparkLine 。 其他一切都一样。

Since we cleared out the template, we no longer need the default styles. So feel free to remove everything from the <style> section.

由于我们清除了模板,因此不再需要默认样式。 因此,请随时从<style>部分中删除所有内容。

Now run the development server.

现在运行开发服务器。

npm run serve

With the server running, we can visit http://localhost:8080/ and see our progress so far.

服务器运行后,我们可以访问http:// localhost:8080 /并查看到目前为止的进展。

It is literally just a horizontal yellow line, which is perfect because that’s exactly what we’ve coded so far.

从字面上看,这只是一条水平的黄线,这是完美的,因为这正是我们到目前为止所编码的。

Let’s code a way to pass data into this component so we can display it using this line.

让我们编写一种将数据传递到此组件的方法,以便我们可以使用此行显示它。

Going back to SparkLine.vue and adding to the script section, define a prop called data. This prop will be an array. We’ll also tell it to simply use a basic array of [0, 0] if no data is passed in.

返回SparkLine.vue并添加到script部分,定义一个称为data的道具。 这个道具将是一个数组。 如果没有数据传入,我们还将告诉它仅使用[0, 0]的基本数组。

<script>export default {  name: "SparkLine",  props: {    data: {      type: Array,      default() {        return [0, 0];      }    }  }};</script>

We can pass data into the component back in App.vue like so:

我们可以像这样将数据传递回App.vue的组件:

<SparkLine :data="[808, 1475, 1426, 1884, 1396]" />

Note that the line above replaces the existing <SparkLine />. Also note that these are just random values I made up. Feel free to use whatever you like.

请注意,上面的行替换了现有的<SparkLine /> 。 还要注意,这些只是我所组成的随机值。 随意使用任何您喜欢的东西。

Now it’s time to use D3.js to bind data to the line. First, install D3.

现在是时候使用D3.js将数据绑定到行了。 首先,安装D3。

npm i d3

Then, in SparkLine.vue, import it at the top of the <script> section.

然后,在SparkLine.vue ,将其导入到<script>部分的顶部。

import * as d3 from "d3";

When the component is mounted, we need to tell D3 to set up the chart. So below the props definition, add a mounted() function.

安装组件后,我们需要告诉D3设置图表。 因此,在props定义下面,添加一个mounted()函数。

export default {  name: "SparkLine",  props: { /* ... snip ... */ },  mounted() {    // We will set up the chart here  }};

Inside the mounted() function, tell D3 where our chart will go.

mounted()函数中,告诉D3我们的图表将去向何处。

this.chart = d3.select("svg"); // Targets the (only) SVG element

Now we need to set up x and y scales. The x axis will start at the very start (0) of our chart and end at the very end (right) of our chart (200).

现在我们需要设置x和y比例尺。 x轴将从图表的开头(0)开始,到图表(200)的结尾(右侧)结束。

this.x = d3.scaleLinear().range([0, 200]);

And the y axis will start at the bottom (40) and end at the top (0) of our chart.

y轴将从图表的底部(40)开始并在顶部(0)结束。

this.y = d3.scaleLinear().range([40, 0]);

If you’ve used D3 scales before, you might be wondering why we’re not setting the domain here. That’s because we’re going to put that logic in a separate function that can get called any time our data changes.

如果您以前使用过D3比例,您可能想知道为什么我们不在这里设置域。 那是因为我们将把该逻辑放在一个单独的函数中,该函数可以在我们的数据更改时随时调用。

Now we must define the line function.

现在我们必须定义line函数。

this.line = d3  .line()  .x((d, i) => this.x(i))  .y(d => this.y(d));

What the code above does, is defines a D3 line where the x value is determined by the position of the data in the array and the y value is determined by the data point itself.

上面的代码定义了一条D3行,其中x值由数组中数据的位置确定,而y值由数据点本身确定。

Finally, let’s call a method to actually plot the data.

最后,让我们调用一个方法来实际绘制数据。

this.plot();

The function called in the line above doesn’t exist, yet. Let’s create it now.

上面一行中调用的函数尚不存在。 现在创建它。

This will go in our components methods.

这将进入我们的组件methods

export default {  name: "SparkLine",  props: { /* ... snip ... */ },  methods: {    plot() {      // Plotting code goes here    }  },  mounted() { /* ... snip ... /* }};

The first thing to do inside of plot() is to set the domain of our scales according to the data.

plot()内部要做的第一件事是根据数据设置比例尺的范围。

this.x.domain([0, this.data.length - 1]);this.y.domain(d3.extent(this.data));

As you can see above, the x scale’s domain starts at 0 and ends at the end of the array. The y scale’s domain starts with the smallest data value and ends with the largest.

如上所示,x比例尺的域从0开始,在数组的末尾结束。 y标度的域以最小的数据值开始,以最大的数据值结束。

Now to actually adjust the chart line. Also in plot():

现在实际调整图表线。 同样在plot()

this.chart.select("path").attr("d", this.line(this.data));

If you save SparkLine.vue and look again at http://localhost:8080/ (assuming the development server is still running), you can see the sparkline!

如果保存SparkLine.vue并再次查看http:// localhost:8080 / (假设开发服务器仍在运行),则可以看到迷你图!

What happens if our data changes? All we need to do is call the plot() method again. Set up a watcher to do that. This watcher will “watch” the data property and call plot() any time it changes.

如果我们的数据改变会怎样? 我们需要做的就是再次调用plot()方法。 设置观察者来执行此操作。 该监视程序将“监视” data属性,并在更改时调用plot()

export default {  name: "SparkLine",  props: { /* ... snip ... */ },  watch: {    data() {      this.plot();    }  },  methods: { /* ... snip ... /* },  mounted() { /* ... snip ... /* }};

And now our component can react to data changes!

现在,我们的组件可以响应数据更改了!

While all of this works as a single component, there’s one important bug that we have to fix if we want to re-use this component more than once on the same page. Right now, we have D3 selecting the sole <svg> element on the page. If you have more than one <svg> on the same page, D3 is just going to select the first one it finds. This is no good. We want to select the <svg> in this component.

尽管所有这些都作为一个单独的组件工作,但是如果我们想在同一页面上多次重复使用此组件,则必须修复一个重要的错误。 现在,我们让D3在页面上选择唯一的<svg>元素。 如果您在同一页面上有多个<svg> ,则D3将选择它找到的第一个。 不好 我们要在组件中选择<svg>

To do that, we can assign our <svg> a unique ID.

为此,我们可以为我们的<svg>分配一个唯一的ID。

First, install nanoid.

首先,安装nanoid 。

npm i nanoid

Import it into our component at the top of the <script> section.

将其导入到<script>部分顶部的组件中。

import { nanoid } from "nanoid";

Create a new id data property and use nanoid to make it random.

创建一个新的id数据属性,并使用nanoid使其随机。

export default {  name: "SparkLine",  props: { /* ... snip ... /* },  data() {    return {      id: `chart-${nanoid()}`    };  },  methods: { /* ... snip ... /*},  mounted() { /* ... snip ... /*}};

We use the template string `chart-${nanoid()}` so that our random id is in the format chart-kHM_8K1yz8GGq6MVBwfoG or chart-VG5J13fYZIdMBrSDRuEBX for example. It’s always random.

我们使用模板字符串`chart-${nanoid()}`以便我们的随机ID的格式为chart-kHM_8K1yz8GGq6MVBwfoGchart-VG5J13fYZIdMBrSDRuEBX 。 它总是随机的。

In the template, set the <svg>'s id to this new id.

在模板中,将<svg>id设置为此新ID。

<svg :id="id" viewBox="0 0 200 40">

Finally, tell D3 to select the element based on this ID.

最后,告诉D3根据该ID选择元素。

Replace

更换

this.chart = d3.select("svg");

with

this.chart = d3.select(`#${this.id}`);

That’s it Our sparkline component is done! You can add multiple sparkline components on the same page and they’ll all show up perfectly.

就是这样,我们的迷你图组件已完成! 您可以在同一页面上添加多个迷你图组件,它们将完美显示。

<template>  <div style="width:100px">    <SparkLine :data="[808, 1475, 1426, 1884, 1396]" />    <SparkLine :data="[3246, 1941, 2649, 1633, 1262]" />    <SparkLine :data="[190, 128, 209, 208, 116]" />  </div></template>

All code for this article is open source and published on GitHub.

本文的所有代码都是开源的,并在GitHub上发布。

In the next article, I’ll show you how to use this component to build a “dashboard” for easy visualization of many data points.

在下一篇文章中,我将向您展示如何使用此组件来构建“仪表盘”,以轻松可视化许多数据点。

Keep an eye out here for the link once it’s published.

发布链接后,请留意此处。

练习给读者 (Exercise to the reader)

The component is hard-coded to have a yellow line. What if you wanted to be able to set the color individually per component? Hint: use a prop (and don’t forget to set a default value!).

该组件被硬编码为黄线。 如果您希望能够为每个组件分别设置颜色怎么办? 提示:使用prop (不要忘记设置默认值!)。

翻译自: https://travishorn.com/build-a-sparkline-vue-component-d3fdec764145

vue 构建根组件


http://www.taodudu.cc/news/show-5715223.html

相关文章:

  • 迷你图——别看我个头小,却是图形显示的利器
  • 怎么恢复U盘删除的内容,U盘的内容被删除了怎么办
  • U盘里的东西删除了还能恢复吗?U盘删除的文件如何恢复
  • U盘数据恢复--Disk Recover In Charge For my workhard
  • foxmail 通讯录同步方法
  • 安卓通讯录项目_【安卓用户】通讯录同步助手使用教程
  • 泰拉瑞亚服务器账号能不能代入,【图片】【教程】如何开一个属于自己的Terraria服务器【terraria吧】_百度贴吧...
  • 关用路由器信道的设置
  • 必联路由器虚拟服务器怎么设置,LB-LINK必联路由器【无线中继】设置教程
  • 【转】无线路由器信道怎么设置
  • 深大计算机专业英语笔试,深大新生入学英语水平测试考什么?英语渣看完瑟瑟发抖......(附3套模拟题)...
  • 2018年职称英语计算机考试,2018年职称英语考试综合A词汇精选试题
  • Servlet——HTTP介绍(帅气、漂亮的都会点赞的哦!!!)
  • 四月英语总结——《坚不可摧》
  • 分享一个集学习、休闲娱乐于一体的帅气个人小站
  • 英语基础-定语概述
  • 英语晨读
  • (安卓)三星手机邮箱设置吉大学生邮箱
  • 小学生一学就会的计算机魔术,小学生一学就会的魔术 小学生一学就会的魔术分享...
  • h5 canvas仿 Photoshop 绘制调色板
  • 分享13个Spring Boot 优质开源项目!商城,ERP,管理系统…
  • 掌控板教程 | 掌控超声波传感器?可能没你想的那么简单!
  • 苍了个天,记一次Linux(被黑客)入侵......
  • 掌控板教程 | 想要掌控超声波传感器?可能没你想的那么简单!
  • 计算机网络入门基础篇——数据链路层(上)
  • 计算机网络-3数据链路层
  • PIE-Engine APP:1984-2021年黄河口及其附近海域的悬浮泥沙、透明度和叶绿素a的结果
  • 光电自动避障小车_手把手教做智能小车
  • Xshell下载更新安装
  • XShell下载安装与使用

vue 构建根组件_构建迷你图Vue组件相关推荐

  1. 韦东山uboot_内核_根文件系统学习笔记4.4-第004课_根文件系统-第004节_构建根文件系统之构建根文件系统

    一 最小的根文件系统需要的项(笔记4.1 4.2小结) (init 进程需要) 打开终端: /dev/console, /dev/NULL 不设置 inittab 格式中的 id(标准输入.输出和标准 ...

  2. vue 添加全局组件_自定义vue2.0全局组件(下篇)

    在上篇中,老K为大家介绍了一个初级自定义按钮组件的编写方法.虽然能用,但是还不算完美,可扩展性不够强大.在这一篇中,老K继续为大家完善这个按钮组件. 启动命令窗口, 进入在上篇中我们搭建的vue目录中 ...

  3. vue避免重新渲染_详解强制Vue组件重新渲染的方法

    在某些情况下,我们必须强制Vue重新渲染组件,如果没有,那可能,你做的业务还不够负责,反正我是经常需要重新渲染组件,哈哈. 虽然Vue不会自动更新这种情况是相对比较少,但是知道如何在出现这个问题时修复 ...

  4. vue 移动端头像裁剪_vue头像上传裁剪组件_一个漂亮的Vue组件,用于图像裁剪和上传...

    vue头像上传裁剪组件 vue-image-crop-upload (vue-image-crop-upload) A beautiful vue component for image crop a ...

  5. vue调试工具如何使用_教你使用Vue.js的DevTools来调试vue项目

    Vue DevTools项目的官方主页位于GitHub上:https://http://github.com/vuejs/vue-devtools.你可以找到安装说明,帮助解决一些问题等等.目前该扩展 ...

  6. dom不刷新 vue 加数据后_高频出现的Vue 面试题及答案

    前言 本文讲解高频出现的 Vue 面试题及答案. 复习前端面试的知识,是为了巩固前端的基础知识,最重要的还是平时的积累! 注意:文章的题与题之间用下划线分隔开,答案仅供参考. Vue 对 MVC.MV ...

  7. vue 单选框样式_作为一位Vue工程师,这些开发技巧你都会吗?

    来源 | http://www.cnblogs.com/chanwahfung/p/12543103.html 路由参数解耦 一般在组件内使用路由参数,大多数人会这样做: export default ...

  8. vue多张图片实现TV端长图浏览组件

    vue多张图片实现长图组件 上一篇写了vue中如何实现长图效果,实现的是单张图片,本文讲解多张图片实现长图,直接上代码: 1.布局代码如下: <template><div class ...

  9. java运行构建期间出错_构建和运行Java 8支持

    java运行构建期间出错 尚未提供对Java 8的Eclipse支持. 如果要使用它,则必须构建它. Eclipsepedia的JDT Core / Java8页面包含有关使用Eclipse Java ...

最新文章

  1. Win8Metro(C#)数字图像处理--2.12Sobel边缘检测
  2. 游戏UI设计(1.2)--Textures Sprite之封装
  3. 我的Ubuntu体验
  4. 脑功能成像研究之我见-组会讲稿
  5. SQLite.NET (32位) 在64位环境中无法正常调试
  6. 暴击!被初中生碾压智商!这份被国家数学集训队采用的初中奥数资料究竟有多厉害?...
  7. python适用的操作系统是_操作系统先来先服务python
  8. [Err] 1093 - You can't specify target table 'xxx' for update in FROM clause解决方法
  9. 大数据之-Hadoop之HDFS_基于JAVA的开发_客户端环境测试---大数据之hadoop工作笔记0055
  10. html 绝对位置居中,如何在div中对绝对定位元素进行居中?
  11. IDEA 创建java项目
  12. u盘启动怎么修复计算机,电脑店u盘启动winpe如何修复系统引导
  13. 好消息!!超任模拟器被我移植到MOTO E680i上了!!
  14. python正则表达式爬取链家租房信息
  15. sudo apt-get update 出现Reading package lists… Error!
  16. 一位小程序代理商亲自见证小程序在外卖行业的突破
  17. 导出https网站证书
  18. 在Solaris下自动启动oracle|Sybase
  19. 浙江杭州工程师职称评审论文要求
  20. 地下暗管探测技术方案——探地雷达(暗管探测仪)

热门文章

  1. 数据可视化制图工具:Echarts(基于JS)
  2. 用vue怎么获选表单元素信息
  3. 超详细JDK1.8安装与配置
  4. 什么是游戏建模 3D游戏建模入门难吗?没有美术基础可以学吗?
  5. 鼠标移走时,鼠标悬停hover样式不消失
  6. halcon 网状产品表面破损检测
  7. EOS CPU价格短暂暴涨百倍真相
  8. vue第三方框架之ElementUi
  9. 颠覆想象——vivo Xplay5人性化体验揭秘
  10. 火车售票排队系统 c语言,【C语言】实现12306火车售票系统!【附源码】