charting-library (tradingview高级图表踩坑日记)
1、library_path 路径问题
图表没法加载???可能是library_path 路径不对导致的,例如在nuxt3框架中配置多语言,语言切换时url路径开头会被加上语言前缀(/zh、/jp等),导致图表没法加载,这时候有多种配置方法,其中有两种较为完美。
- 使用绝对路径加载资源。
确保 Charting Library 的所有静态资源(如 datafeeds 和其他依赖文件)使用绝对路径加载,而不是相对路径,且确保charting_library 的资源放在 public/charting_library/ 目录下。然后在 Nuxt 项目中修改配置:
// 在 nuxt.config.ts 中配置 runtimeConfig 或全局变量,定义资源的绝对路径。
export default defineNuxtConfig({
runtimeConfig: {
public: {
chartingLibraryBasePath: '/charting_library/',
},
},
});
// 在加载 Charting Library 时使用绝对路径:
const basePath = useRuntimeConfig().public.chartingLibraryBasePath;
const widget = new TradingView.widget({
container_id: "tv_chart_container",
library_path: basePath, // 使用绝对路径
datafeed: new Datafeeds.UDFCompatibleDatafeed(`${basePath}datafeeds/udf/`),
});
// 其他配置...
- 动态检测语言前缀并修正路径
可以通过 Nuxt 的 useRouter 检测当前的语言路径,并修正加载的资源路径。
// 检测当前语言路径:
const router = useRouter();
const currentLang = router.currentRoute.value.path.split('/')[1]; // 获取语言前缀
const basePath = currentLang === 'en' ? '/charting_library/' : `/${currentLang}/charting_library/`;
// 动态配置 Charting Library 的路径:
const widget = new TradingView.widget({
container_id: "tv_chart_container",
library_path: basePath, // 动态设置语言前缀路径
datafeed: new Datafeeds.UDFCompatibleDatafeed(`${basePath}datafeeds/udf/`),
// 其他配置...
});