如何在Vue.js项目中集成使用TradingView图表Widget组件?
Vue.js 接入TradingView图表的正确实现方案
步骤1:全局引入TradingView依赖
不要在组件内直接插入script标签加载tv.js,直接在项目public/index.html的head标签内加入资源引用:
<script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
步骤2:编写单文件组件模板
在你需要使用图表的Vue组件的template部分,只保留容器节点即可,不需要内嵌script:
<template> <div class="tradingview-widget-container"> <div id="tradingview_bf88f"></div> <div class="tradingview-widget-copyright"> <a href="https://www.tradingview.com/symbols/NASDAQ-AAPL/" rel="noopener" target="_blank"> <span class="blue-text">AAPL Chart</span> </a> by TradingView </div> </div> </template>
步骤3:生命周期中初始化图表
需要等待DOM挂载完成后再初始化TradingView实例,Vue2和Vue3的写法分别如下:
Vue2 写法
<script> export default { name: 'TradingViewChart', data() { return { tvInstance: null } }, mounted() { // 确保TradingView全局对象已加载 if (window.TradingView) { this.tvInstance = new window.TradingView.widget({ "width": 980, "height": 610, "symbol": "NASDAQ:AAPL", "interval": "D", "timezone": "Etc/UTC", "theme": "dark", "style": "1", "locale": "en", "toolbar_bg": "#f1f3f6", "enable_publishing": false, "allow_symbol_change": true, "container_id": "tradingview_bf88f" }) } }, beforeDestroy() { // 组件销毁前清理实例,避免内存泄漏 if (this.tvInstance) { this.tvInstance.remove() this.tvInstance = null } } } </script>
Vue3 写法
<script setup> import { ref, onMounted, onBeforeUnmount } from 'vue' const tvInstance = ref(null) onMounted(() => { if (window.TradingView) { tvInstance.value = new window.TradingView.widget({ "width": 980, "height": 610, "symbol": "NASDAQ:AAPL", "interval": "D", "timezone": "Etc/UTC", "theme": "dark", "style": "1", "locale": "en", "toolbar_bg": "#f1f3f6", "enable_publishing": false, "allow_symbol_change": true, "container_id": "tradingview_bf88f" }) } }) onBeforeUnmount(() => { if (tvInstance.value) { tvInstance.value.remove() tvInstance.value = null } }) </script>
注意事项
- 如果你需要适配响应式宽度,可以把width参数设为
"100%",配合外层容器的宽度控制即可 - 配置项可以根据需求动态修改,切换交易对时直接重新实例化或者调用TradingView实例的API修改参数即可
- 如果出现
TradingView is not defined的报错,检查index.html的资源是否加载成功,或者在初始化前加个资源加载完成的监听逻辑
内容的提问来源于stack exchange,提问作者user16070299
相关产品推荐
相关产品推荐

