在自己的项目中用到了图表,虽然Echarts很火但是......默认样式比较丑,所以选择了阿里的图表库Antv的G2plot组件。
因为我使用了基于Nuxt的Vue SSR,所以当服务端渲染的时候,会报比较常见的document不存在错误。官方文档关于这种使用插件的方法有相关描述,不过提供了很多种方案,初学者第一次遇到相关问题的时候可能不知道如何选择。在我尝试搜索的时候,网络上大多推荐使用静态js方案引入,或者通过添加到config中的plugin并且启用仅浏览器载入。这些方案测试的时候单独使用都不是很适合价值G2plot(如果有人尝试成功了的话请联系我修改)。
经过一番测试下来,官网提供的注入Vue实例的方法最适合,文档中是这样描述的:
有时您希望在整个应用程序中使用某个函数或属性值,此时,你需要将它们注入到Vue实例(客户端),context(服务器端)甚至 store(Vuex)。按照惯例,新增的属性或方法名使用
$
作为前缀。将内容注入Vue实例,避免重复引入,在Vue原型上挂载注入一个函数,所有组件内都可以访问(不包含服务器端)。
官方文档链接为:
https://zh.nuxtjs.org/guide/plugins#%E4%BD%BF%E7%94%A8%E7%AC%AC%E4%B8%89%E6%96%B9%E6%A8%A1%E5%9D%97
具体使用步骤为:
安装:
(省略nuxt配置的部分)
npm install @antv/g2plot
或
yarn add npm @antv/g2plot
注入Vue实例:
//plugins/g2.js
import Vue from 'vue'
let g2 = require("@antv/g2plot")
Vue.prototype.$g2 = g2
//nuxt.config.js
export default {
plugins: [
{
src: "~/plugins/g2",
ssr: false
},
],]
}
使用:
<div id="c1"></div>
//import { Bar } from '@antv/g2plot';
const Bar = this.$g2.Bar
const data = [
{ year: '1951 年', sales: 38 },
{ year: '1952 年', sales: 52 },
{ year: '1956 年', sales: 61 },
{ year: '1957 年', sales: 145 },
{ year: '1958 年', sales: 48 },
];
const barPlot = new Bar('c1', {
data,
xField: 'sales',
yField: 'year',
colorField: 'year',
});
barPlot.render();
即可正常使用啦√