v1.0.1html
一個 chart-x 標籤搞定數據可視化, omi 和 chart.js強力加持git
<chart-bar />
柱狀圖<chart-line />
線圖<chart-scatter />
散點圖<chart-pie />
餅圖<chart-doughnut />
環狀圖<chart-radar />
雷達圖<chart-polar-area />
極區圖<chart-bubble />
氣泡圖npm i omi-chart
複製代碼
import 'omi-chart'
define('my-app', class extends WeElement {
install(){
this.chartData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: '#f391a9',
borderColor: '#ef5b9c',
borderWidth: 1
}]
}
this.chartOptions = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
render(props, data) {
return (
<div>
<chart-bar width={600} data={this.chartData} options={this.chartOptions} />
</div>
)
}
})
render(<my-app />, 'body')
複製代碼
具體的傳入 options 和 data 格式能夠查看 chart.js 文檔。github
代碼量很少,直接看源碼:npm
import { WeElement, define } from 'omi'
import Chart from 'chart.js'
class ChartBase extends WeElement {
receiveProps(props) {
this.chart.data = props.data
this.chart.options = props.options
this.chart.update()
}
render(props) {
return (
<div style={{ width: props.width + 'px', height: props.height + 'px' }}> <canvas ref={(e) => { this.canvas = e }}> </canvas> </div>
)
}
}
define('chart-bar', class extends ChartBase {
installed() {
this.chart = new Chart(this.canvas.getContext('2d'), {
type: this.props.horizontal ? 'horizontalBar' : 'bar',
data: this.props.data,
options: this.props.options
})
}
})
define('chart-line', class extends ChartBase {
installed() {
this.chart = new Chart(this.canvas.getContext('2d'), {
type: 'line',
data: this.props.data,
options: this.props.options
})
}
})
define('chart-scatter', class extends ChartBase {
installed() {
this.chart = new Chart.Scatter(this.canvas.getContext('2d'), {
data: this.props.data,
options: this.props.options
})
}
})
複製代碼
全部的圖表繼承自 ChartBase,ChartBase 繼承自 WeElement。omi-chart 會根據傳入的 props 建立不一樣類型的 Chart。canvas
其中利用了勾子函數 receiveProps。瀏覽器
receiveProps - 當父組件從新刷新的時候會觸發改勾子函數。bash
預告一下:Omi 立刻要支持 IE9 和全部的移動端瀏覽器,敬請期待。app