Adding a chart-js plugin to vue-chart-js - vue.js

I'm trying to add a chartjs plugin called chartjs-plugin-annotation (https://github.com/chartjs/chartjs-plugin-annotation) to my vue-chart js project. In my BarChart.vue file, I first imported the chartjs annotation plugin
<script>
import { Bar, mixins } from "vue-chartjs";
import chartjsPluginAnnotation from "chartjs-plugin-annotation";
const { reactiveProp } = mixins;
export default {
extends: Bar,
mixins: [reactiveProp],
plugins: {
annotation: {
drawTime: "afterDatasetsDraw",
events: ["click"],
dblClickSpeed: 350,
annotations: [
{
drawTime: "afterDraw",
id: "a-line-1",
type: "line",
mode: "horizontal",
scaleID: "y-axis-0",
value: "25",
borderColor: "red",
borderWidth: 2,
onClick: function (e) {
// `this` is bound to the annotation element
},
},
],
},
},
props: {
options: {
type: Object,
required: true,
},
},
mounted() {
// add plugin
this.addPlugin([chartjsPluginAnnotation]);
this.renderChart(this.chartData, this.options);
},
watch: {
options() {
this.renderChart(this.chartData, this.options);
},
},
};
</script>
I added the plugin under mounted() this.addPlugin([chartjsPluginAnnotation]);, before rendering the chart.
Am I adding the config options to my chart correctly as at the plugins : ?
I've installed the plugin successfully, using npm install chartjs-plugin-annotation --save. I refreshed my app on my local but there's no annotation plugin added to the chart. What am I supposed to fill up in the onClick: function (e)? What am I still missing?
I apologise in advance because I'm really new to this framework.

Here's how your options object should look like:
{
...
annotation: {
annotations: [
{<your annotation object code here>}
],
},
...
}
Next, you've correctly identified that you should use the addPluing() method, just make sure to use it like so
// in imports
import SomePlugin from "..."
// in mounted
this.addPlugin(SomePlugin);

https://stackoverflow.com/a/65486537/7165219
import chartjsPluginAnnotation from "chartjs-plugin-annotation";
And:
mounted() {
Chart.plugins.register(chartjsPluginAnnotation);
this.addPlugin(chartjsPluginAnnotation);
this.renderChart(this.chartData, this.options);
}

Related

Nuxt: Module should export a function: #turf/helpers [ERROR]

Does anyone know why am I getting Module should export a function: #turf/helpers when I add #turf/helpers to my buildModules in nuxt.config.js?
nuxt.config.js
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/tailwindcss
'#nuxtjs/tailwindcss',
'#turf/helpers'
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
],
Am I adding the module to the wrong array?
FYI: the module is present within my package.json / dependencies. Thus, the installation went through.
// Component where import { point } from '#turf/helpers' returns undefined
<script>
import { defineComponent } from '#vue/composition-api';
import mapboxgl from 'mapbox-gl';
import { point } from '#turf/helpers'
export default defineComponent({
data () {
return {
geojson: {
'type': 'FeatureCollection',
'features': []
},
map: null,
}
},
mounted() {
this.initMapBox();
},
methods: {
// Initialize MapBox map
initMapBox: function() {
mapboxgl.accessToken = 'pk.eyJ1IjoiYWxleGFuZHJ1YW5hIiwiYSI6ImNrZTl3NzJ3bzIxNG4yc2w2aG03dHNkMDUifQ.xaSxrVMLZtfGAlWoGvB1PQ';
this.map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/alexandruana/cksxeq0637zjy17tcvd4h919d',
center: [22.253, 45.419],
zoom: 4
});
this.map.on('load', () => {
console.log('Map loaded.')
let point = point([22.253, 45.419]);
console.log(point)
this.map.addSource('points', {
type: 'geojson',
data: this.geojson
});
this.map.addLayer({
id: 'points',
type: 'circle',
source: 'points',
paint: {
'circle-radius': 8,
'circle-color': '#00a9e2'
},
filter: ['in', '$type', 'Point']
});
});
},
}
})
Importing it as a regular NPM package and using it without colliding with the same variable name fixed the issue!
Indeed, this was not a Nuxt module.

Is there a way to use Vanta.js effects in a Nuxt.js project?

I am currently making a personal portfolio site using Nuxt.js (using TypeScript).
I decided I want to use Vanta.js Halo effect. for my landing page, but I can't seem to find a way to make it work properly.
I tried using three.js and vanta npm packages, but it produces an error.
'Cannot read property “texture” of undefined'
import * as THREE from 'three'
import HALO from 'vanta/dist/vanta.halo.min.js'
...
*inside Vue.extend block*
mounted(){
this.vantaEffect = HALO({
el: '#landing',
*rest of the settings*
THREE: THREE
})
}
Is there any way I can make it work?
Update:
I managed to get rid of the errors using static files - method from this vanta repo issue, but static script for initiating can't find the #landing element.
/*nuxt.config.js*/
...
head: {
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: process.env.npm_package_description || '',
},
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
script: [
{ src: 'vanta.halo.min.js' },
{ src: 'three.min.js' },
{ src: 'effect.js' },
],
},
...
/*effect.js - file that initializes the effect*/
VANTA.HALO({
el: '#landing',
mouseControls: true,
touchControls: true,
gyroControls: false,
minHeight: 200.0,
minWidth: 200.0,
baseColor: 0xffffff,
backgroundColor: 0x2d2d2d,
THREE,
})
Update 2:
I managed to fix the problem with not finding the #landing element by exporting a function that initializes the effect and running it from the mounted() and passing the element reference.
/*effect.js*/
const vantaEffect = (elementRef) => {
return window.VANTA.HALO({
el: elementRef,
mouseControls: true,
touchControls: true,
gyroControls: false,
minHeight: 200.0,
minWidth: 200.0,
THREE: THREE,
})
}
export default vantaEffect
Now this error shows up:
[VANTA] Init error TypeError: Cannot read property 'LinearFilter' of undefined
So, I fiddled a bit with the sandbox that Lawrence provided, and I was able to make it work like this: https://codesandbox.io/s/winter-thunder-pffsq
Basically what happens is that Vanta assumes that THREE is set on window, which doesn't happen when we import it from npm. So you must import Vanta after you import THREE and set it as a window variable.
import * as THREE from "three";
// import HALO from "vanta/dist/vanta.halo.min";
export default {
async mounted() {
// window is only avaiable on browser
if (process.browser) {
window.THREE = THREE;
const { default: HALO } = await import("vanta/dist/vanta.halo.min");
HALO({
el: "#abc",
mouseControls: true,
touchControls: true,
minHeight: 200.0,
minWidth: 200.0,
xOffset: -0.17,
size: 2.1,
THREE: window.THREE
});
}
}
};

Is it possible to substitute Vue.extend with new Vue?

I am working on a Quasar project and I am having a problem. I need to access from external javascript to the properties and methods of the Vue component.
const vue = Vue.extend({
name: 'PageIndex',
data() {
return {
accessToken:
'myToken',
mapStyle: 'mapbox://styles/mapbox/streets-v11',
coordinates: { lng: -82.42642875898966, lat: 23.11975881338755 },
barbershopsSource: {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: {
title: 'Foo'
},
geometry: {
type: 'Point',
coordinates: [-82.42644475189455, 23.119620627441506]
}
},
{
type: 'Feature',
properties: {
title: 'Bar'
},
geometry: {
type: 'Point',
coordinates: [-82.42193696725194, 23.124402891576594]
}
},
{
type: 'Feature',
properties: {
title: 'Baz'
},
geometry: {
type: 'Point',
coordinates: [-82.43414198682088, 23.115900071933567]
}
}
]
}
};
},
components: {},
methods: {
createMap() {
mapboxgl.accessToken = this.accessToken;
const map = new mapboxgl.Map({
container: 'map',
style: this.mapStyle, // stylesheet location
center: this.coordinates, // starting position [lng, lat]
zoom: 15 // starting zoom
});
const source = this.barbershopsSource;
map.on('load', function() {
console.log('Map loaded');
//I want to have access to the component properties here
});
map.on('click', 'barbershops', function(e) {
console.log('Barbershop clicked:', e.lngLat);
});
}
},
mounted() {
this.createMap();
}
});
export default vue;
I know that access to properties is pretty simple, but the thing is that by default and I don't know why, Quasar uses Vue.extend to create the components. If I substitute
const vue = Vue.extend
by
const vue = new Vue
I can access to properties, but the component view isn't loaded.
Any help would be greatly appreciated
The way it works is, quasar takes App.vue as the entry point and loads the generated compiled javascript. The app is created there.
There is only one app running.
You add functionality to your vue app by extend the app.
You create app once in App.vue and add functionality to it by extending.

How add ScrollMagic in nuxt project?

I am trying to add ScollMagic in my Nuxt project, I followed this article: https://nuxtjs.org/guide/plugins & I've added ScrollMagic.js in nuxt.config.js and I got this issue: ReferenceError window is not defined.
module.exports = {
plugins: [
{ src: '~plugins/ScrollMagic', mode: 'client' }
],
}
Then I've added this snippet in my component:
import ScrollMagic from 'scrollmagic'
I still have this issue...
Even if cover it like this:
if (process.client) {
Vue.use(ScrollMagic)
}
I know this question is a bit old, but maybe someone will find my sulotion helpfull.
EDIT: Also, this way you can register any plugin to nuxt :).
So what I did:
1.
npm i scrollmagic
Go to nuxt.config.js and add the following to your plugins section:
{ src: '~/plugins/ScrollMagic.js', mode: 'client' }
This will make sure that scrollmagic will only be included in the client. This prevents the window undefined error.
Go to the plugins folder, or make it in your root folder and make a new file called ScrollMagic.js. In here add the following:
import Vue from 'vue';
import * as ScrollMagic from 'scrollmagic';
Object.defineProperty(Vue.prototype, '$scrollmagic', { value: ScrollMagic });
This snippet will make the variable $scrollmagic available in every component/page. You can call this.$scrollmagic to use it. For example const controller = new this.$scrollmagic.Controller();
Hope this helps anyone.
This is answering Drew Baker.
I think you are making it more complicated than it should be. Using GSAP with Nuxt is fairly simple.
npm install gsap in your terminal.
In the file you want to animate something, import gsap. In the script tag: import { gsap } from 'gsap'.
use GSAP like you're used too. const lt = gsap.timeline();.
If you still want to use GSAP as I explained in the other comment:
Follow the steps 1 & 2 from the other comment.
In step 3 of the previous comment, create a file called 'gsap.js' in there import Vue and GSAP.
import Vue from 'vue';
import { gsap } from 'gsap';
Object.defineProperty(Vue.prototype, '$gsap', { value: gsap });
Hope this helps you #Drew Baker!
currently what works is to use the cdn and integrate in 'nuxt.config.js'.
Like this :
head: {
...
script: [
{
src: "https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js",
async: 'async',
ssr: false,
defer: true,
body: true,
},
{
src: "https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/debug.addIndicators.min.js",
async: 'async',
ssr: false,
defer: true,
body: true,
},
] },
in the component :
export default {
mounted () {
if (process.client) {
var controller = new ScrollMagic.Controller()
var scene = new ScrollMagic.Scene({ triggerElement: '#trigger1' })
// exemple : trigger animation by adding a css class
.setClassToggle('#animate1', 'zap')
.addIndicators({ name: '1 - add a class' }) // add indicators (requires plugin)
.addTo(controller)
}
}}
you can use this method for other puglins that wouldn't work on nuxt by using npm or [puglins]
use the cdn and integrate in 'nuxt.config.js'.
script: [
{
src: "https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js",
async: 'async',
ssr: false,
defer: true,
body: true,
},
{
src: "https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/debug.addIndicators.min.js",
async: 'async',
ssr: false,
defer: true,
body: true,
},
{
src: "https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/animation.gsap.min.js",
async: 'async',
ssr: false,
defer: true,
body: true,
},
] },
In component
Anim() {
if (process.browser && window) {
const ScrollMagic = window.ScrollMagic;
const bookTimeline = new TimelineMax({});
bookTimeline
.from(".hmbookservice-container", 0.6, {
yPercent: 20,
opacity: 0,
ease: Power4.easeOut,
clearProps: "all"
})
.from(
".hmservice-textwrap h4",
0.6,
{
xPercent: 20,
opacity: 0,
ease: Power4.easeOut,
clearProps: "all"
},
"-=.1"
)
.from(
".hmservice-btnwrap",
0.6,
{
xPercent: 20,
opacity: 0,
ease: Power4.easeOut,
clearProps: "all"
},
"-=.2"
);
const bookController = new ScrollMagic.Controller();
const bookAnimScene = new ScrollMagic.Scene({
triggerElement: ".hmbookservice-container",
reverse: false,
offset: -200
})
.setTween(bookTimeline)
.addTo(bookController);
}
}
mounted() {
if (process.browser && window) {
this.Anim();
}
}
For Vue / Nuxt projects you can use vue-scrollmagic plugin.

vue-chartjs how to load data

Linechart.js
import { Line } from 'vue-chartjs'
export default {
extends: Line,
props:['chart']
mounted () {
this.renderChart({
labels: ['1','2','3','4','5','6','7'],
datasets: [
{
label: 'Data One',
backgroundColor: '#F64A32',
data: this.chart
}
]
}, {responsive: true, maintainAspectRatio: false})
}
}
I use the props to pass the data
example.vue
<template>
<line-chart :width="370" :height="246" :chart="chartdata"></line-chart>
</template>
<script>
import LineChart from './vue-chartjs/LineChart'
export default {
components: {
LineChart
},
},
data(){
return{
chartdata:[]
}
}
methods:{
getdata(){
this.chartdata=[10,20,30,40,50]
}
}
</script>
when I click the getdata() the chartdata I think it has been passed to the Linechart.js, But why the chart does not update? Still empty
If you want the data to change on the fly, you either need the reactiveMixin http://vue-chartjs.org/#/home?id=reactive-data
Or you have to trigger an chart update by yourself.
This is because, even Vue.js is reactive, Chart.js per se is not.
If you want to update your chart, simply add a watcher to your LineChart.js component and watch for changes in chart. And then call .update()
import { Line } from 'vue-chartjs'
export default {
extends: Line,
props:['chart']
watch: {
chart () {
this.$data._chart.update()
}
}
mounted () {
this.renderChart({
labels: ['1','2','3','4','5','6','7'],
datasets: [
{
label: 'Data One',
backgroundColor: '#F64A32',
data: this.chart
}
]
}, {responsive: true, maintainAspectRatio: false})
}
}