How can I use javascript library function in nuxt.js? - javascript

This source worked in html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kakao JavaScript SDK</title>
<script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
<script>
// SDK를 초기화 합니다. 사용할 앱의 JavaScript 키를 설정해 주세요.
Kakao.init('JAVASCRIPT_KEY');
// SDK 초기화 여부를 판단합니다.
console.log(Kakao.isInitialized());
</script>
</head>
<body></body>
</html>
So I thought the next source will work on Nuxt.js.
But it showed just
'ReferenceError
Kakao is not defined' in these source
in nuxt.config.js
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
title: 'P-Cloud OCR',
meta: [
{ 'http-equiv': 'X-UA-Compatible', content: 'IE=Edge' },
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
script: [
{ src: 'https://developers.kakao.com/sdk/js/kakao.js'},
]
}, ```
in pages/login.vue
<script>
export default {
...
}
Kakao.init('JAVASCRIPT_KEY');
console.log('Kakao.isInitialized() >>', Kakao.isInitialized());
</script>
Why is this source not working?

There are basically 2 approaches you can do:
1. Load the library directly in your layout/page/component
head () {
if (window.Kakao) {
this.afterKakaoLoaded()
return
}
return {
script: [
{
hid: 'kakao',
src: 'https://developers.kakao.com/sdk/js/kakao.js',
callback: () => {
this.afterKakaoLoaded()
}
}
]
}
},
methods: {
afterKakaoLoaded () {
window.Kakao.init('...')
}
}
2. Load the library within a plugin
Josh Deltener wrote a great article about how to achieve that: https://deltener.com/blog/nuxt-third-party-code-is-poison/

In nuxt you can overwrite the default .nuxt/views/app.template.html.
You need to create app.html file at the root of the project. Then put the below code inside this file:
app.html
<!DOCTYPE html>
<html lang="en" {{ HTML_ATTRS }}>
<head {{ HEAD_ATTRS }}>
{{ HEAD }}
</head>
<body {{ BODY_ATTRS }}>
{{ APP }}
</body>
</html>
Then you can follow the traditional way that you mentioned in question:
<!DOCTYPE html>
<html lang="en" {{ HTML_ATTRS }}>
<head {{ HEAD_ATTRS }}>
{{ HEAD }}
<script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
<script>
// SDK를 초기화 합니다. 사용할 앱의 JavaScript 키를 설정해 주세요.
Kakao.init('JAVASCRIPT_KEY');
// SDK 초기화 여부를 판단합니다.
console.log(Kakao.isInitialized());
</script>
</head>
<body {{ BODY_ATTRS }}>
{{ APP }}
</body>
</html>
But be aware that in this method, all pages in your application load this script.

Related

MathJax not processing latex environments

I am writing a blog post on blogspot. Here is my MathJax configuration in the theme's html file.
<script defer='defer' id='MathJax-script' src='https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-svg.js' type='text/javascript'/>
<script>
window.MathJax = {
tex: {
loader: {load: ['[tex]/ams']},
inlineMath: [ ['$','$'],['\\(','\\)'] ],
displayMath: [ ['$$','$$'], ['\\[','\\]'] ],
processEscapes: true,
processEnvironments: true,
processRefs: true,
packages: {
'[+]': ['ams']
},
},
};
</script>
And here is my attempt at using the amsmath align environment.
...
By linearity of expectation
\begin{align}
\mathbb{E}[I_r] & \leq |I_{r-1}|+\sum_{u\in \overline{I_{r-1}}\setminus \{v_{r-1}\}}{\mathbb{E}[X_{u,r}]}+1\\
& \leq |I_{r-1}| + c_2k(|\overline{I_{r-1}}|-1)|I_{r-1}|/n^2+1\\
& \leq |I_{r-1}|\cdot(1+c_2k/n) + 1\\
\end{align}
...
However, when previewing my page, it just renders the text literally, without MathJax processing. How can I fix this?
This works perfectly. Hope it works for you.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
MathJax = {
tex: {
inlineMath: [
['$', '$'],
['\\(', '\\)']
]
},
svg: {
fontCache: 'global'
}
};
</script>
<script type="text/javascript" id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-chtml.js">
</script>
</head>
<body>
<div class="math">
\begin{align}
\mathbb{E}[I_r] & \leq |I_{r-1}|+\sum_{u\in \overline{I_{r-1}}\setminus \{v_{r-1}\}}{\mathbb{E}[X_{u,r}]}+1\\
& \leq |I_{r-1}| + c_2k(|\overline{I_{r-1}}|-1)|I_{r-1}|/n^2+1\\
& \leq |I_{r-1}|\cdot(1+c_2k/n) + 1\\
\end{align}
</div>
</body>
<script>
const
math = document.querySelector('.math')
MathJax.typeset();
</script>
</html>

Passing data in array that came from an array to chartjs with django

So, I'm trying to pass some data to a chart (using chartjs and django) and I can print my data in my webpage, but can't pass it as arguments to the chart. Also, if I put data hardcoded in the chart it works, but with my own data from an array I can't see anything...
I've tried {{data | safe}} and {{labels | safe}} but I get an error, so I'm not getting what I'm doing wrong. Can anyone help me?
To explain better:
views.py
import csv
def home(request):
csvFilePath = "../data/raw_datasets/covid_confirmed.csv"
data = []
labels = []
with open(csvFilePath, "r") as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
next(csv_reader)
for row in csv_reader:
data.append(row[1])
labels.append(row[73])
return render(request, 'home.html',
{
'data': data,
'labels': labels
})
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<title>Crypto Covid</title>
</head>
<body>
<h4>{{data | safe}}</h4>
<p>--------------</p>
<h4>{{labels|safe}}</h4>
<div class="container">
<canvas id="chart">
</canvas>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<script> src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"</script>
<script>
var config = {
type: 'pie',
data: {
datasets: [{
data: {data} ,
backgroundColor: [
'#696969', '#808080', '#A9A9A9', '#C0C0C0', '#D3D3D3'
],
label: 'Population'
}],
labels: {labels}
},
options: {
responsive: true
}
};
window.onload = function() {
var ctx = document.getElementById('chart').getContext('2d');
window.myPie = new Chart(ctx, config);
};
</script>
</html>
The result in my page:
my result page
you need to use template tag called json_script, {{ your_array|json_script:"chart_data" }} and then access this data in javascript -
var value = JSON.parse(document.getElementById('chart_data').textContent);
https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#json-scriptDjango documentation
Try this please
import csv
def home(request):
csvFilePath = "../data/raw_datasets/covid_confirmed.csv"
data_list = []
with open(csvFilePath, "r") as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
next(csv_reader)
for row in csv_reader:
data_list.append({'label' : row[73], "y" : row[1]})
t = json.dumps(data_list)
return render(request, 'home.html',
{
'output':t
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<title>Crypto Covid</title>
</head>
<body>
<div id="pie-chart" style="width: 100%;height:370px;">
</div> <!-- edited -->
</body>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> <!-- edited--></script>
<!-- edited -->
data = JSON.parse("{{ output|escapejs }}")
window.onload = function() {
var chart = new CanvasJS.Chart("pie-chart", {
type: 'pie',
data: [{type: "pie",dataPoints: data}],
options: {
responsive: true
}
});
chart.render();
};
</script>
</html>
Try passing the data list by list (I use render_template on Flask) and retrieve it on javascript (as an array) with:
labels: [{% for item in families %}
"{{ item }}",
{% endfor %}]
...even if pylint may say criticize the html syntaxe. It runs well.

FusionCharts not Updating in React

When trying to update a chart in React using the sample given by FusionCharts, I can't get the chart to update. It is definitely changing the value, which I found out by adding this line:
console.log(revenueChartConfigs.dataSource.data[2].value);
The value is changing from 590000 to 420000 as desired, but the chart does not update. Does anyone have advice on this? I have pasted my code below. Thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/fusioncharts.js"></script>
<script type="text/javascript" src="js/fusioncharts.charts.js"></script>
<script type="text/javascript" src="js/fusioncharts.gantt.js"></script>
<script type="text/javascript" src="js/fusioncharts.maps.js"></script>
<script type="text/javascript" src="js/fusioncharts.powercharts.js"></script>
<script type="text/javascript" src="js/fusioncharts.ssgrid.js"></script>
<script type="text/javascript" src="js/fusioncharts.treemap.js"></script>
<script type="text/javascript" src="js/fusioncharts.widgets.js"></script>
<script type="text/javascript" src="js/fusioncharts.zoomscatter.js"></script>
<script src="https://unpkg.com/react#15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/react-fusioncharts.min.js"></script>
<script type='text/babel'>
$(document).ready(function(){
var myDataSource = {
chart: {
caption: "Top 5 stores in last month by revenue",
subCaption: "Harry's SuperMart",
numberPrefix: "$",
theme: "fint"
},
data: [{
label: "Bakersfield Central",
value: "880000"
}, {
label: "Garden Groove harbour",
value: "730000"
}, {
label: "Los Angeles Topanga",
value: "590000"
}, {
label: "Compton-Rancho Dom",
value: "520000"
}, {
label: "Daly City Serramonte",
value: "330000"
}]
};
var RevenueChart = React.createClass({
/**
** `getInitialState()` method is used to initialize the state of the
** the `RevenueChart` component.
**/
getInitialState: function () {
return {
eventTarget: ''
};
},
/**
** The `handleClick()` function is defined in the `RevenueChart` component.
** This function is configured to store the state of the `eventTarget` using
** the `setState()` method of React. This is binded to button click.
**/
handleCLick: function () {
this.setState({
eventTarget: 'btn-update-data'
});
},
render: function () {
var revenueChartConfigs = {
id: "revenue-chart",
renderAt: "revenue-chart-container",
type: "column2d",
width:600,
height: 400,
dataFormat: "json",
dataSource: myDataSource,
eventTarget: this.state.eventTarget,
impactedBy: ['btn-update-data']
};
/**
** Using the state, we update the `label` and `value` for the third and
** fourth data plots in the `render()` method of RevenueChart. The configuration
** object that is passed as props is used to refer to the `label`
** and `value` attributes of the `data` object array.
**/
if (this.state.eventTarget && this.state.eventTarget.length != 0) {
revenueChartConfigs.dataSource.data[2].label = "Art Supply Store";
revenueChartConfigs.dataSource.data[2].value = "420000";
revenueChartConfigs.dataSource.data[3].label = "P.C. Richard & Son";
revenueChartConfigs.dataSource.data[3].value = "320000";
}
else {
revenueChartConfigs.dataSource = myDataSource;
}
console.log(revenueChartConfigs.dataSource.data[2].value);
return (
<div>
/** The `FusionCharts` React component is used to render the chart. **/
<react_fc.FusionCharts {...revenueChartConfigs} />
/** Create a button, which when clicked will call the `handleClick()` function. **/
<a id='btn-update-data'
onClick={this.handleCLick}
className="btn btn-default"
href="#">{'Click me to change data'}</a>
</div>
);
}
});
ReactDOM.render(
<RevenueChart />,
document.getElementById('chart-container')
);
});
</script>
</head>
<body>
Hello
<div id="chart-container"></div>
</body>
</html>

Polymer custom-row-style in paper-datatable

I try set custom-row-style in paper-datatable. demo
This is working code:
<!doctype html>
<html>
<head>
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/paper-datatable/paper-datatable.html">
</head>
<body>
<template is="dom-bind" id="app">
<paper-datatable data="{{data}}" custom-row-style="{{generateRowCss}}" >
<paper-datatable-column header="Calories" property="calories"></paper-datatable-column>
</paper-datatable>
</template>
<script>
var app = document.querySelector('#app');
app.data = [
{id: 0, title: 'Frozen yogurt', calories: 159},
{id: 0, title: 'Frozen yogurt', calories: 159}
];
app.generateRowCss = function(item){
return 'background:red;';
};
</script>
</body>
</html>
generateRowCss is a property, not a function
If I try insert in my module:
var app2 = document.querySelector('#idModule');
or var app2 = document.getElementById('idModule');
app2.generateRowCss = function(item){return 'background:red;';};
app2 return null
Best way for me - to use the properties of the polymer:
Polymer({
is: 'idModule',
properties: {
generateRowCss: {
type: String,
value: "background:red;"
or function(item){return 'background:red;';}
or computed: '_generateRowCss(item)'
},
However, this causes errors in the polymer modules:
Uncaught TypeError: this.customRowStyle is not a function.

Put ExtJS form on javascript method call

I'm totaly net to javascript and ExtJS. So maybe someone can help me.
I want to display ExtJS made form on Web page when I call javascript method.
The code is:
.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Car Wiki</title>
<link rel="stylesheet" type="text/css" href="extJSLib\extjs-4.1.1\resources\css\ext-all.css">
<script type="text/javascript" src = "extJSLib\extjs-4.1.1\ext-all-dev.js"></script>
<link rel ="stylesheet" type="text/css" href="mainPageStyle.css">
<script type = "text/javascript" src="mainPageScript.js"></script>
</head>
<body>
<div class="mainForm" >
<div id="mainPanel">
<script>mainModule.testMethos();</script>
</div>
</div>
</body>
</html>
mainPageScript.js
(function(exports){
exports.testMethos = function()
{
var formPanel = Ext.create('Ext.form.Panel',{
title: 'Search Form',
width:300,
height:200,
layout: 'anchor',
defaults:
{
anchor:'80%'
},
renterTo: document.body,
items:[
{
xtype: 'textfield',
fieldLabel: 'Car Name',
name: 'carName',
labelAlign: 'top',
cls: 'field-margin',
flex:1
},
{
xtype: 'textfield',
fieldLabel: 'Car Model',
name:'carModel',
labelAlign:'top',
cls:'field-margin',
flex: 1
}
]
});
};
} )(this.mainModule = {});
where is my mistake? (do not say, that in my genetic code :D)
First mistake is your use of Ext.onReady as this is an event which gets fired when the framework has finished loading.
Trying to use it within a function call like you have makes no sense, so just remove this altogether and just keep your form code.
Alternatively, you can still use Ext.onReady but it should be used in the main script block of your html file, that and your form code should be moved there.
I have got your form to display using this approach, you can see this working here
Fiddle above

Categories

Resources