在Vue項目中使用d3.js的實(shí)例代碼
之前寫一個 Demo里面 有些東西要使用d3實(shí)現(xiàn)一些效果 但是在很多論壇找資源都找不到可以在Vue里面使用D3.js的方法,npm 上面的D3相對來說 可以說是很不人性化了 完全沒有說 在webpack上怎么使用D3.js
最后折騰很久 看到某位外國大佬 看他的案例 成功的實(shí)現(xiàn)了在Vue項目里面實(shí)現(xiàn)D3的使用
首先安裝
npm install d3 --save-dev
以防萬一,然后看package.json
安裝完成
在我們開始之前,讓我們渲染一個Vue組件,它使用常規(guī)的D3 DOM操作呈現(xiàn)一個簡單的折線圖:
<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>
代碼簡單易懂,但這僅僅是一個基本的例子。因為我們沒有使用模板,所以需要更多操作和計算的更復(fù)雜的可視化會掩蓋組件的設(shè)計和邏輯。上述方法的另一個警告是,我們不能使用scopedCSS 的屬性,因為D3會動態(tài)地向DOM添加元素。
可以使用比較奇怪,但是代碼比較優(yōu)雅的方式去實(shí)現(xiàn)
<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>
非常酷,即使它沒有公開任何屬性并且數(shù)據(jù)是硬編碼的,它很好地將視圖從邏輯中分離出來,并且使用Vue鉤子,方法和data對象,現(xiàn)象和上圖一樣的。
總結(jié)
以上所述是小編給大家介紹的在Vue項目中使用d3.js的實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
相關(guān)文章
Vue實(shí)現(xiàn)模糊查詢的簡單方法實(shí)例
這篇文章主要給大家介紹了關(guān)于Vue實(shí)現(xiàn)模糊查詢的簡單方法,在vue中,前端模糊搜索主要是用computed屬性實(shí)現(xiàn),本文通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08Vue一個動態(tài)添加background-image的實(shí)現(xiàn)
這篇文章主要介紹了Vue一個動態(tài)添加background-image的實(shí)現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03elementPlus?的el-select在提示框關(guān)閉時自動彈出的問題解決
這篇文章主要介紹了elementPlus?的el-select在提示框關(guān)閉時自動彈出閉時自動彈出的問題,主要問題就是因為filterable屬性,根本解決方案是選中的時候讓他失去焦點(diǎn)?el-select有一個visible-change事件,下拉框出現(xiàn)/隱藏時觸發(fā),感興趣的朋友跟隨小編一起看看吧2024-01-01Electron自動更新失效報錯Error:?Object?has?been?destroyed的問題解決
本文主要講解如何解決?Error:?Object?has?been?destroyed?這個?Electron?中最常見的問題,以及?Electron?自動更新的流程,文中通過代碼示例給大家講解的非常詳細(xì),需要的朋友可以參考下2024-01-01