uni-app(vue3.x版本) 实现k线图(kline) 支持h5/安卓/ios

uni-app 的插件市场有 https://ext.dcloud.net.cn/plugin?id=4591
因为我之前用的kline是使用klineChart https://klinecharts.com/zh-CN
config也配置好了,所有就没有使用插件市场的kline,接着使用klineChart
第一步 安装 klineChart

npm install klinecharts --save

第二步 在页面中绘制元素

<template>
    <view id="chart"></view>
</template>

第三步 将容器变canvas
注:因为uni-app 的app端是没有document的对象,且 <template>标签下 需要一个最大的标签包裹起来 不然会出现问题
(H5端着没有问题 可以参考:https://www.jianshu.com/p/869684c81e89 实现)
所以绘制 uni-app 采用的是 renderjs
官方文档:
https://uniapp.dcloud.net.cn/component/canvas.html#canvas
https://uniapp.dcloud.net.cn/tutorial/renderjs.html

// 将第二步变为
<template>
 <!-- 
  id: id值
  :newest : 最新值
  :history : 历史数据
  :change:newest : 监听最新值是否变化 (renderScript 对应下边 script 标签上的 module="renderScript")
  :change:history : 监听历史数据是否变化 (renderScript 对应下边 script 标签上的 module="renderScript")
 -->
    <view 
           id="chart"   
           :newest="klineNewest" 
           :history="klineHistory" 
           :change:newest="renderScript.updateNewest" 
           :change:history="renderScript.updateHistory">
    </view>
</template>
<script setup>
  import { onMounted,ref } from 'vue'
  import { init } from 'klinecharts' 
  // 历史
  const klineHistory = ref([])
  // 最新
  const klineNewest = ref({})
 // 获取kline 历史数据
  const getKlineHistory = ()=>{
   //http请求 略
    klineHistory .value = data
  }
  // 获取kline 最新数据 (webscoket)
  const webscoketKline = () => {
   //scoket请求 略
    klineNewest.value = data
  }
  onMounted(()=>{
    kline = init('chart', config)
  }) 
</script>
<!-- script  setup 不支持 lang="renderjs" 后也不支持uni-app 的各种方法(uni.xxx) -->
<script module="renderScript" lang="renderjs">
    import { config } from './klineConfig.js'
    import klinecharts from 'klinecharts'
    var kline
    export default {
        mounted() {
            this.initChart()
        },
        methods: {
            initChart() {
                kline = klinecharts.init('chart')
                kline.setStyleOptions(config)
                kline.createTechnicalIndicator('MA', false, { id: 'candle_pane'})
                kline.setStyleOptions({
                    technicalIndicator: { tooltip: { showRule: 'none'}}
                })
            },
            //监听最新值变化 注: kline值可能还没有  所以需要 kline?.
            updateNewest(newValue, oldValue, ownerInstance, instance) {
                // 添加最新数据 
                kline?.updateData(newValue)
            },
           //监听历史数据变化  注: kline值可能还没有  所以需要 kline?.
            updateHistory(newValue, oldValue, ownerInstance, instance) {
                // 添加历史数据 
                kline?.applyNewData(newValue)
            }
        }
    }
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容