由淺入深的 D3.js 初級及進階指南 之一 HelloWorld
任何教程的開端離不開 hello world ,我們也不能免俗. D3.js 擁有中非常強大的對 DOM 進行操作的能力.現在就簡單的操作一下.
所需環境:
- ember-cli v3.16.1
- node v10.16.0
- d3.js v5
環境搭建詳見 由淺入深的 D3.js (v5/v4) 初級及進階指南 之零 背景介紹與環境安裝
0. 前言
select
方法在 D3.js 中佔據中重要的位置.任何 DOM 操作的起點.可以通過此方法,獲取到想要操作的 DOM.
這也就是告訴我們,在框架中使用 D3.js 的時候,需要在組件元素或其他元素插入到文檔中,大概就是 didInsert
這個聲明週期之後,才能進行對 DOM 的操作.
1. 使用 D3.js 展示 Hello world 文本
1.1 創建 d3/hello-world 組件
ember g component d3/hello-world
原生 JavaScript 的話及可以直接在頁面中添加 p 標籤.
修改 handlerbars :
<p class="d3-hello" {{did-insert this.hello}}></p>
修改 component 邏輯文件:
import Component from '@glimmer/component';
import { action } from '@ember/object';
import {select} from 'd3-selection';
interface D3HelloWorldArgs {}
export default class D3HelloWorld extends Component<D3HelloWorldArgs> {
@action
hello() {
select(".d3-hello").text("HELLOWORLD BY D3")
}
}
在路由中使用此組件:
{{!-- d3 route file --}}
<h2>d3-1 helloworld</h2>
<D3::HelloWorld />
此時運行文件即可以看到:
同樣的:
import Component from '@glimmer/component';
import { action } from '@ember/object';
import {select} from 'd3-selection';
interface D3HelloWorldArgs {}
export default class D3HelloWorld extends Component<D3HelloWorldArgs> {
@action
hello() {
let p = select(".d3-hello").text("HELLOWORLD BY D3");
// 修改此元素的樣式
p.attr("title","helloWorld").style("color","lightblue")
}
}
這樣就可以改變字體的 style 樣式了,併爲此 P 標籤添加了 title 屬性,雖然沒有什麼作用。
更多的關於 d3-selection 的 API 請查看鏈接。
2. 使用 .datum() / .data() 綁定數據
同樣的創建 d3/bind-data 組件。
{{!-- d3/bind-data.hbs --}}
<p class="d3-bind" {{did-insert this.dataBind}}></p>
<p class="d3-bind" {{did-insert this.dataBind}}></p>
<p class="d3-bind" {{did-insert this.dataBind}}></p>
<p class="d3-bind" {{did-insert this.dataBind}}></p>
<p class="d3-bind2" {{did-insert this.dataBind2}}></p>
<p class="d3-bind2" {{did-insert this.dataBind2}}></p>
// d3/bind-data.ts
import Component from '@glimmer/component';
import { selectAll } from 'd3-selection';
import { action } from '@ember/object';
interface D3BindDataArgs { }
const STR = "DATABIND";
const ARR = ["落霞與孤鶩齊飛","秋水共長天一色"];
export default class D3BindData extends Component<D3BindDataArgs> {
@action
dataBind() {
let p = selectAll('.d3-bind');
p.datum(STR)
p.text(function (d, i) {
return `✨第 ${i} 個元素綁定的值是 ${d}✨`
})
}
@action
dataBind2() {
let ps = selectAll(".d3-bind2");
ps.data(ARR).text(function(d) {
return d
})
}
}
同樣的,在路由中使用此組件:
{{!-- d3 route file --}}
<h2>d3-1 helloworld</h2>
<D3::HelloWorld />
<div class="dropdown-divider"></div>
<h2>d3-2 bind-data</h2>
<D3::BindData />
運行程序可以看到:
3. 總結
在這篇文章中,對 D3.js 中 select
及其相關方法應該是有比較深刻的瞭解,如果沒有,那麼在以後的教程中我們也是會經常看到的.
更多關於 select
及其相關方法也可以查看此處 .
本系列其他文章:
- 環境搭建
- hello world (使用 D3.js 創建文本並綁定數據)