Inserting Vanilla JS into VueJS framework - javascript

With the concept of VueJS is a kind of framework of JS, then it should have no problem inserting the vanilla JS into it. The following is the attempt to insert the pure JS code into vue-cli project(webpack structure).
[Before Start] I tried the example code as the following link(official document)
URL: https://codepen.io/Tobyliao/pen/ZEWNvwE?editable=true%3Dhttps%3A%2F%2Fdocs.bokeh.org%2F
it works.
[Question] As I tried to imlement into Vue project. It fails. picture1 is the directory structure.
I tried to place the src url include into ./public/html's tag as following:
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.2.1.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.2.1.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.2.1.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-api-2.2.1.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-api-2.2.1.min.js"></script>
Create a componet in './src/components/BokehPlot.vue'
inside the code, I insert
<template>
<h1>Measurement Plotting</h1>
</template>
<script src='./main.js'>
export default {
}
</script>
Then finally place all the Bokeh code into './src/component/main.js'. It is the pure JS code I want to import into the structure.
[Result]
I can see the plot in the background, but it kept on showing the error message like picture2.

You have many options here, I went ahead and simply made a mixin to utilize the component lifecycle that Vue provides. source
Here are the relevant parts:
BokehPlot.vue
<template>
<h1>治具量測</h1>
</template>
<script>
import Chart from "#/mixins/Chart";
export default {
mixins: [Chart],
};
</script>
Chart.js
export default {
data() {
return {
plot: null,
xdr: null,
ydr: null
};
},
beforeMount() {
// create some ranges for the plot
this.xdr = new Bokeh.Range1d({ start: -1, end: 100 });
this.ydr = new Bokeh.Range1d({ start: -0.5, end: 20.5 });
// make the plot
this.plot = new Bokeh.Plot({
title: "BokehJS Plot",
x_range: this.xdr,
y_range: this.ydr,
plot_width: 400,
plot_height: 400,
background_fill_color: "#F2F2F7"
});
},
mounted() {
this.loadData();
},
methods: {
loadData() {
// create some data and a ColumnDataSource
let x = Bokeh.LinAlg.linspace(-0.5, 20.5, 10);
let y = x.map(function (v) {
return v * 0.5 + 3.0;
});
let source = new Bokeh.ColumnDataSource({ data: { x: x, y: y } });
// add axes to the plot
let xaxis = new Bokeh.LinearAxis({ axis_line_color: null });
let yaxis = new Bokeh.LinearAxis({ axis_line_color: null });
this.plot.add_layout(xaxis, "below");
this.plot.add_layout(yaxis, "left");
// add grids to the plot
let xgrid = new Bokeh.Grid({ ticker: xaxis.ticker, dimension: 0 });
let ygrid = new Bokeh.Grid({ ticker: yaxis.ticker, dimension: 1 });
this.plot.add_layout(xgrid);
this.plot.add_layout(ygrid);
// add a Line glyph
let line = new Bokeh.Line({
x: { field: "x" },
y: { field: "y" },
line_color: "#666699",
line_width: 2
});
this.plot.add_glyph(line, source);
Bokeh.Plotting.show(this.plot);
}
}
};
Many decisions to still make, but hopefully that will get you pointed down the right path.
See working example:
https://codesandbox.io/s/bokehjs-forked-4w20k?fontsize=14&hidenavigation=1&theme=dark

Related

tui-image-editor not showing properly

tui-image-editor not showing properly. Why? What am I doing wrong?
Version: 3.15.3
code:
import "./styles.css";
var ImageEditor = require("tui-image-editor");
var FileSaver = require("file-saver"); //to download edited image to local. Use after npm install file-saver
// var blackTheme = require("darktheme");
var locale_ru_RU = {
// override default English locale to your custom
Crop: "Обзрезать",
"Delete-all": "Удалить всё"
// etc...
};
var instance = new ImageEditor(document.querySelector("#tui-image-editor"), {
includeUI: {
loadImage: {
path: "img/sampleImage.jpg",
name: "SampleImage"
},
locale: locale_ru_RU,
// theme: blackTheme, // or whiteTheme
initMenu: "filter",
menuBarPosition: "bottom"
},
cssMaxWidth: 700,
cssMaxHeight: 500,
selectionStyle: {
cornerSize: 20,
rotatingPointOffset: 70
}
});
result:
sandbox where I got this result https://ryy3zx.csb.app. Same on my rails application.
Solved problem putting
<link
rel="stylesheet" href="https://uicdn.toast.com/tui-image-editor/latest/tui-image-editor.css"
/>
inside head tag in application.html file. You can put anywhere before element with tui-image-editor

How to create chart in google sheets with javascript?

I am using javascript to create Google-sheets-document with user data. The document is saved on the user's Drive.
I can't figure out how to make a graph from the data i have inserted. I am using vanilla javascript with the Google sheets API.
It would probably look something like this:
function createGraph() {
gapi.client.sheets.graph
.create({
properties: {
type(?): 'Pie'
spreadsheetid: //some id
range: 'A1:A10'
},
})
}
EDIT: To specify, i want to insert the graph to the sheets-document that i have created, not to the website.
If you want to add the chart to your spreadsheet, you can use Sheets API's AddChartRequest, as part of the spreadsheets.batchUpdate method.
Code snippet:
On broad terms, your request would look like this (check the reference below in order to build the request body in detail):
const payload = {
"requests": [
{
"addChart": {
"chart": {
"spec": { // Chart type, range source, etc.
"pieChart": { // Pie chart specification
// object (PieChartSpec)
}
// rest of ChartSpec properties
},
"position": { // Where the chart will be located
// object (EmbeddedObjectPosition)
}
}
}
}
]
}
const params = {
spreadsheetId = "YOUR-SPREADSHEET-ID",
body = payload
}
gapi.client.sheets.spreadsheets.batchUpdate(params);
Render chart in browsers and mobile devices:
In case you just wanted to render the chart in a browser, but not add it to your spreadsheet, you would use Google Charts (see Visualization: Pie Chart, for example).
Reference:
Sheets API > Charts
EmbeddedChart
ChartSpec
EmbeddedObjectPosition
PieChartSpec
Refer this example
<html>
<head>
<!--Load the AJAX API-->
<script
type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"
></script>
<script type="text/javascript">
var data;
var chart;
// Load the Visualization API and the piechart package.
google.charts.load("current", { packages: ["corechart"] });
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create our data table.
data = new google.visualization.DataTable();
data.addColumn("string", "Topping");
data.addColumn("number", "Slices");
data.addRows([
["Mushrooms", 3],
["Onions", 1],
["Olives", 1],
["Zucchini", 1],
["Pepperoni", 2]
]);
// Set chart options
var options = {
title: "How Much Pizza I Ate Last Night",
width: 400,
height: 300
};
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart(
document.getElementById("chart_div")
);
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width: 400; height: 300;"></div>
</body>
</html>
Referred from
https://developers.google.com/chart/interactive/docs/drawing_charts
I solved it. Thanks for the help! This worked for me.
function createGraphv2(spreadsheetIdGraph, endIndex) {
var params = {
// The spreadsheet to apply the updates to.
spreadsheetId: spreadsheetIdGraph, // TODO: Update placeholder value.
};
var batchUpdateSpreadsheetRequestBody = {
// A list of updates to apply to the spreadsheet.
// Requests will be applied in the order they are specified.
// If any request is not valid, no requests will be applied.
requests: [
{
addChart: {
chart: {
spec: {
title: 'Rapport',
basicChart: {
chartType: 'COLUMN',
legendPosition: 'BOTTOM_LEGEND',
axis: [
//X-AXIS
{
position: "BOTTOM_AXIS",
title: "FORBRUK"
},
//Y-AXIS
{
position: "LEFT_AXIS",
title: "TID"
}
],
series: [
{
series: {
sourceRange: {
sources: [
{
sheetId: 0,
startRowIndex: 0,
endRowIndex: endIndex,
startColumnIndex: 5,
endColumnIndex: 6,
},
],
},
},
targetAxis: "LEFT_AXIS"
}
]
}
},
position : {
newSheet : 'True'
}
},
}
}
],
// TODO: Add desired properties to the request body.
};
var request = gapi.client.sheets.spreadsheets.batchUpdate(
params,
batchUpdateSpreadsheetRequestBody
);
request.then(
function (response) {
// TODO: Change code below to process the `response` object:
console.log(response.result);
},
function (reason) {
console.error("error: " + reason.result.error.message);
}
);
}

Bind plotly on click to vue.js data

I am creating project with vue.js and plot.ly javascript graph library.
How can I bind in "pts" to vue's data's "TestSentences"?
Here is my code ,
thank you to everyone who contributed
My goal is to create an interactive dashboard using this variable. In this way, I can change the data by clicking anywhere on the chart.
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="app">
<div id="grafik"></div>
</div>
<!-- Vue-->
<script>
var app = new Vue({
el: '#app',
data: {
TestSentences: "",
},
methods: {
grafikCiz() {
var trace1 = {
x: [1, 2, 3],
y: ["book", "pencil", "bag"],
mode: 'markers',
marker: {
color: ['#6886c5', '#f40552', '#1b1b2f'],
size: [10, 20, 30]
}
};
var data = [trace1];
var layout = {
height: 400,
width: 400,
};
Plotly.newPlot('grafik', data, layout);
},
},
mounted: function () {
this.grafikCiz();
},
});
</script>
<!-- Vue -->
<script>
var my_graph = document.getElementById('grafik');
my_graph.on('plotly_click', function (data) {
for (var i = 0; i < data.points.length; i++) {
pts = 'x = ' + data.points[i].x + '\ny = ' + data.points[i].y + '\n\n';
};
alert('Closest point clicked:\n\n' + pts);
});
</script>
Use plolty wrapper for vue.js https://github.com/David-Desmaisons/vue-plotly
You can add ref to the component
<vue-plotly v-show="display" :data="graphData" :layout="calculatedLayoutSizes" id="3dPlot"
:display-mode-bar="false" ref="crazyPlotly"></vue-plotly>
then use the ref within your mount point or similar method
this.$refs.crazyPlotly.$on('click', d => {
console.log(d);
});
"d" is an obj with values like x and y datapoint, index...etc
source: https://github.com/statnett/vue-plotly/issues/23
As Alagappan A already pointed out, https://github.com/David-Desmaisons/vue-plotly can make working with plotly in javascript much easier. For me it was sufficient to just:
<vue-plotly :data="data" :layout="layout" #click="temp"> </vue-plotly>
which can directly be utilized in a method:
methods: {
temp (value) {
console.log(value)
}
}

Chart.js chart by passing data through the controller MVC

I am trying to display a chart by passing to it data from a controller. I am using chart.js
Model:
public class DatapointLine
{
public DatapointLine(double x, double y)
{
this.X = x;
this.Y = y;
}
// setting the name to be used when serializing to JSON.
[DataMember(Name = "x")]
public Nullable<double> X = null;
//setting the name to be used whenserializing to JSON.
[DataMember(Name = "y")]
public Nullable<double> Y = null;
}
Controller:
public JsonResult BarChart()
{
List<DatapointLine> dataPoints = new List<DatapointLine>{
new DatapointLine(10, 22),
new DatapointLine(20, 36),
new DatapointLine(30, 42),
new DatapointLine(40, 51),
new DatapointLine(50, 46),
};
ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);
return Json(dataPoints, JsonRequestBehavior.AllowGet);
}
Script:
<script type="text/javascript">
$(function() {
var data = getData();
AutoFollow(data);
});
function getData() {
var dateValue = [];
var countValue = [];
$.ajax({
url: "/Supernethome/BarChart",
dataType: 'json',
async: false
}).done(function(data) {
data.forEach(function(data) {
dateValue.push(data.X);
countValue.push(data.Y);
});
});
return {
dateValue: dateValue,
countValue: countValue
};
}
$(document).ready(function () {function AutoFollow(data) {
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx,
{
type: 'bar',
data: {
labels: data.dateValue,
datasets: [
{
label: 'AutoFollow',
data: data.countValue,
backgroundColor: "rgba(153,255,51,1)"
}, {
label: 'Manual',
data: [30, 29, 5, 5, 20, 3, 10],
backgroundColor: "rgba(255,153,0,1)"
}
]
}
});
}
});
I am generating the views for the charts in partial views and then referencing the partial views in a main view.
I am getting the following errors:
chartjs.init.js:3 Uncaught TypeError: Cannot read property 'getContext' of null
at HTMLDocument.<anonymous> (chartjs.init.js:3)
at f (jquery.js:1026)
at Object.fireWith [as resolveWith] (jquery.js:1138)
at Function.ready (jquery.js:427)
at HTMLDocument.xt (jquery.js:97)
The error is eating a lot of time,Need Help.
Looks like two different errors to me...
Error 1 : Graph container element not found
Checkout this thread as the issue sounds the same:
morris.js Graph container element not found
Error 2 : Cannot read property 'getContext'
This looks like a red herring. This exception is not being thrown by morris.js but by chartjs. However it may be that the exception thrown by this code is stopping the morris.js code from being executed successfully. As such it's worth testing the code in isolation i.e load up a view with nothing in it except the required morris scripts/assets and your inline script. No additional scripts or JavaScript libraries. Something like this :
Example Test View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
</head>
<body>
<div id="mychart"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script>
$(document).ready(function () {
$.getJSON("/Supernethome/BarChart", function (data) {
new Morris.Area({
element: 'mychart',
data: data,
xkey: 'X',
ykeys: ['Y'],
pointSize: 2,
hideHover: 'auto',
resize: true
});
});
});
</script>
</body>
</html>

How to pass VueJS data to another script?

I'm converting an established site over to VueJS but hit a stumbling block on the best way to achieve this.
It's using D3-Funnel (https://github.com/jakezatecky/d3-funnel) to draw a funnel chart but how do I pass VueJS data variables to the charts constructor?
<script>
const data = [
{ label: 'Step 1', value: this.step1 },
{ label: 'Step 2', value: this.step2 },
.......
];
const options = {
block: {
dynamicHeight: true,
minHeight: 15,
},
};
const chart = new D3Funnel('#funnel');
chart.draw(data, options);
</script>
So I need to pass vue data variables into the values. My first thought is to move this into it's own function in the VueJS methods object and use the variables there using this.
Is there a better way of achieving this?
---------- Edit -------------
As per comments people wanted to see how I achieved this currently in vue. As already mentioned above I just created a function in the vue methods object and then call it.
methods : {
drawChart(){
const data = [
{ label: 'Step 1', value: 99999 },
{ label: 'Step 2', value: 9999 },
.......
];
const options = {
block: {
dynamicHeight: true,
minHeight: 15,
},
};
const chart = new D3Funnel('#funnel');
chart.draw(data, options);
}
},
mounted(){
this.drawChart();
}
Data is coming from an API and put into the vue data object.
data:{
step1: 0,
step2: 0,
....
},
methods:{
getData(){
axois.post......
response{
this.step1 = response.data.step1
this.step2 = response.data.step2
....
}
}
}
As I understand it you are trying to pass information down to a component and use it. If you are using single file components and webpack you can do something like this which is put together with examples listed on the vue website.
You can also take a look at this guys approach
App.vue
...
<my-d3-component :d3data="d3Data"></my-d3-component>
...
<script>
import d3Component from 'path/to/component'
var app = new Vue({
el: '#app',
data: {
d3Data: {}
},
components: {
'my-d3-component': d3Component
}
})
</script>
d3Component.vue
<template>
d3 html stuff goes here
</template>
<script>
export default {
props: ['d3Data'],
data() {
return {}
},
mounted: {
const options = {
block: {
dynamicHeight: true,
minHeight: 15,
},
};
const chart = new D3Funnel('#funnel');
chart.draw(this.d3Data, options);
}
}
</script>

Categories