Vue js:ready event not working - javascript

I am trying to load a simple alert in mounted event but its not fired
Here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>
</head>
<body>
<div id="app-7">
</div>
</body>
</html>
script
new Vue({
el: '#app-7',
data: {
groceryList: [
{ text: 'Vegetables' },
{ text: 'Cheese' },
{ text: 'Whatever else humans are supposed to eat' }
],
origin:'http://s3.myimage.com/avatar.jpg'
},
mounted:function () {
console.log('ready');
alert('ok');
}
})
Also i want to set origin into an img after the page load.
Is it possible with vue??

Have you rendered it to your #app-7?
For your 2nd question, yes it's possible, you can set it up like
<img :src="origin" />
Then your img will take its source from your 'origin' string.-7

Related

Vue.js 2: converting a string in a function call at an event handler

In Vue.js 2 I would like to convert a string into a function call so that it can be set as an event handler.
I believe this would be very practical, specially when dynamically creating lots of elements (e.g. buttons) based on a list of objects.
new Vue({
el: "#app",
data: {
myArray: [
{ value: 1, fn: "firstMethod" },
{ value: 2, fn: "secondMethod" },
],
},
methods: {
firstMethod() {
console.log("'firstMethod' was executed.");
},
secondMethod() {
console.log("'secondMethod' was executed.");
},
},
});
<!DOCTYPE html>
<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>
</head>
<body>
<div id="app">
<template v-for="elem in myArray">
<button #click="elem.fn"> <!-- Here is where I am stucked. -->
<!-- <button> -->
{{elem.value}}
</button>
</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<script src="script.js"></script>
</body>
</html>
My first attempt at doing this was setting the fn properties in myArray as sort of pointers to the corresponding functions with this (e.g. fn: this.firstMethod). The problem is, I believe, that at the time of the definition, these functions are still unkown, as I get: [Vue warn]: Invalid handler for event "click": got undefined.
Is what I am trying to achieve even possible? Is there a downside with this strategy that I am overlooking?
Try to create one method, which will be working with all buttons
new Vue({
el: "#app",
data: {
myArray: [
{ value: 1, fn: "firstMethod" },
{ value: 2, fn: "secondMethod" },
],
},
methods: {
basicMethod(name) {
console.log(`'${name}' was executed.`);
if(name === 'firstMethod') {
//some logic, and so on for other methods if u need
}
},
},
});
<!DOCTYPE html>
<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>
</head>
<body>
<div id="app">
<template v-for="elem in myArray">
<button #click="basicMethod(elem.fn)"> <!-- Here is where I am stucked. -->
<!-- <button> -->
{{elem.value}}
</button>
</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<script src="script.js"></script>
</body>
</html>
You can use a generic method provided with the function name the call this[ fn ]();.
But for security reasons, you might want these custom methods to be in an object, not just on the main this, so other methods can't be called.
Also, you want to check if the method exists before calling it.
It would look something like this:
new Vue({
el: "#app",
data: {
myArray: [
{ value: 1, fn: "firstMethod" },
{ value: 2, fn: "secondMethod" },
{ value: 3, fn: "nonExistingMethod" }, // Won't throw an error
{ value: 4, fn: "someImportantSecureMethod" }, // Won't be called
],
customMethods: {
firstMethod: function() {
console.log("'firstMethod' was executed.");
},
secondMethod: function() {
console.log("'secondMethod' was executed.");
},
},
},
methods: {
callCustomMethod(fn) {
// Make sure it exists
if (typeof this.customMethods[fn] === "function") {
// Only methods inside the customMethods object are available
this.customMethods[fn]();
}
},
someImportantSecureMethod() {
console.log('The method may not be exposed to dynamic calling!');
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template v-for="elem in myArray">
<button #click="callCustomMethod(elem.fn)">
<!-- <button> -->
{{elem.value}}
</button>
</template>
</div>
As a side note:
You might also considering using custom events (see docs) for this. Using $emit('custom-event-name') as the v-on:click handler and have your custom methods as event listeners. (Makes it easy when you later might want to make the items into separate components.)

How to incorporate chart.js in jsp file

I am new in javascript and have to use the libraries of Chart.js
I have in a jsp file the following instruction for a button
window.open("test.jsp", "width="+800+ "height="+580);
and in the test.jsp file this code:
<!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">
<title>test</title>
<script type=“text/javascript”>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/Chart.min.js"></script>
<script type=“test.jsp”>
<script type=“text/javascript”>
var ctx = document.getElementById('myChart');
var stars = [135850, 52122, 148825, 16939, 9763];
var frameworks = ['React', 'Angular', 'Vue', 'Hyperapp', 'Omi'];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: frameworks,
datasets: [{
label: 'Github Stars',
data: stars
}]
},
})
</head>
<body>
<canvas id="myChart" width="800" height="400"></canvas>
</body>
</html>
I am able to open the new window but I can't see anything inside.
I would like to all the code runs in jsp file, without delegating to js and html files outside.
There are different problems in your code.
The referenced Chart.js library does not exist. Instead of ...Chart.min.js, write ...chart.min.js (lowercase).
Define your custom JS code in a function and execute it only once the body and its canvas are fully loaded (<body onload="drawChart()">).
Please take a look at below runnable HTML code, it should run similarly with JSP.
<!DOCTYPE html>
<html lang="en">
<head>
<title>test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script type="text/javascript">
function drawChart() {
var stars = [135850, 52122, 148825, 16939, 9763];
var frameworks = ['React', 'Angular', 'Vue', 'Hyperapp', 'Omi'];
new Chart('myChart', {
type: 'bar',
data: {
labels: frameworks,
datasets: [{
label: 'Github Stars',
data: stars
}]
},
});
}
</script>
</head>
<body onload="drawChart()">
<canvas id="myChart" width="800" height="400"></canvas>
</body>
</html>

Getting an error when trying to add a new block to EditorJS manually

Context
I've created a two column page, one column with a button on the left and editorJS on the right column.
What I am trying to do is whenever I click on the button to the left, I want it to be copied into a new block of EditorJS.
Replication
The error triggers whenever trying to add a new block manually (in this case, an extertal button to add more content to EditorJS) using editor.blocks.insert(blockToAdd). Independently of the configuration of the EditorJS, even the most basic one will trigger this error.
Code
index.js (I've modified this file to make it shorter, the error always trigger in the same place which is
const blockToAdd = {
type: 'paragraph',
data: {
text: 'My header'
}
};
editor.blocks.insert(blockToAdd); // Here
Actual file
const btn = document.getElementById('export-btn')
const editor = new EditorJS({
/**
* Id of Element that should contain Editor instance
*/
onReady: () => {
new DragDrop(editor);
},
holder: 'editorjs',
tools: {
header: {
class: Header,
config: {
placeholder: 'Enter a header',
levels: [1,2,3,4],
defaultLevel: 3
}
},
paragraph: {
class: Paragraph,
inlineToolbar: true,
}
},
});
function saveEditor() {
editor.save().then( savedData => {
fetch('http://localhost:3000', {
method: 'POST',
body: JSON.stringify(savedData),
headers: {
'Content-Type': 'application/json'
}
}).then( msg => {
console.log(msg)
}).catch( err => {
console.error(err)
})
console.log()
})
.catch( err => {
console.error(err)
})
}
btn.addEventListener('click', function() {
const blockToAdd = {
type: 'paragraph',
data: {
text: 'My header'
}
};
editor.blocks.insert(blockToAdd);
});
index.html
<!DOCTYPE html>
<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">
<link rel="stylesheet" href="style.css">
<title>Testing EditorJS and Docx</title>
</head>
<body>
<div class="col-left">
<div id="export-btn" class="export-btn">Export to...</div>
</div>
<div class="col-right">
<div id="editorjs"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/#editorjs/editorjs#latest"></script>
<script src="https://cdn.jsdelivr.net/npm/#editorjs/header#latest"></script>
<script src="https://cdn.jsdelivr.net/npm/#editorjs/list#latest"></script>
<script src="index.js"></script>
</body>
</html>
Error
Uncaught TypeError: can't access property "name", s is undefined
S https://cdn.jsdelivr.net/npm/#editorjs/editorjs#latest:6
value https://cdn.jsdelivr.net/npm/#editorjs/editorjs#latest:6
value https://cdn.jsdelivr.net/npm/#editorjs/editorjs#latest:6
<anonymous> https://cdn.jsdelivr.net/npm/#editorjs/editorjs#latest:6
<anonymous> file:///E:/wdev/tasktag-dashboard-ui/index.js:105
EventListener.handleEvent* file:///E:/wdev/tasktag-dashboard-ui/index.js:97
editorjs#latest:6:44399
Error screenshot
Where could the problem be at? Because I am using <script src="https://cdn.jsdelivr.net/npm/editorjs-drag-drop#latest"></script> sort of imports?
Otherwise, I don't know what the problem is. Thank you in advance.
So the problem was in the object I pass to the editor.blocks.insert(blockToInsert).
It requires to pass option by option instead a single object. So the correct solution would be:
const blockToAdd = {
type: 'paragraph',
data: {
text: 'My header'
}
};
editor.blocks.insert(blockToAdd.type, blockToAdd.data);
Thanks Thomas from a JavaScript Telegram community for helping me out to resolve this problem.

How do I call Javascript code from Dart and register the callback in my console?

I have a Javascript file that I'm calling in my Flutter Webview Plugin.
I am trying to return the callback in the console after the onReward method is called. This is the code of my js file:
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="https://s3.amazonaws.com/cdn.theoremreach/v3/theorem_reach.min.js"></script>
</head>
<body>
<iframe src="https://theoremreach.com/respondent_entry/direct?api_key=845783b32b8bef12f1b55a36a8be&user_id=12345"></iframe>
<script type="text/javascript">
var theoremReachConfig = {
apiKey: "",
userId: "12345",
onRewardCenterOpened: onRewardCenterOpened,
onReward: onReward,
onRewardCenterClosed: onRewardCenterClosed
};
var TR = new TheoremReach(theoremReachConfig);
function onRewardCenterOpened(){
console.log("onRewardCenterOpened");
}
function onReward(data){
console.log("onReward: " + data.earnedThisSession);
}
function onRewardCenterClosed(){
console.log("onRewardCenterClosed");
}
if (TR.isSurveyAvailable()) {
TR.showRewardCenter();
}
</script>
</body>
</html>
And this is how I'm calling it in my Dart file:
...
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Reward earned"), actions: [
Text("$reward"),
]),
body: WebViewPlus(
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (controller) {
controller.loadAsset(
'assets/tr.html',
);
},
));
}
When I complete a survey I get the following message in my console:
I/chromium( 3560): [INFO:CONSOLE(28)] "onReward: 2", source: http://localhost:56537/assets/tr.html (28)
I want to scan this console message and just add the value of the reward, i.e. 2, in my existing page and display it in the appBar.

Cannot render interactive image using gojs

I would like to create an interactive image using goJs, however when i try and follow the tutorial to create a basic visual the output I get is just a blank box and not an interactive image with the words 'Alpha' and 'Beta' connected by a line.
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/gojs/release/go-debug.js"></script>
<script src="go.js"></script>
<script>
function init() {
var $ = gp.GraphObject.make;
myDiagram = $(go.Diagram, "decisionTree");
var nodeDataArray = [
{ key: "Alpha" },
{ key: "Beta" }
];
var linkDataArray = [
{ to: "Beta", from: "Alpha" }
];
myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray)
}
</script>
</head>
<body onload="init"()>
<div id="decisionTree" style="width:300px; height:300px; border:1px solid black;"></div>
</body>
</html>
Tutorial: https://www.youtube.com/watch?v=7cfHF7yAoJE#action=share
You are loading two different versions of the GoJS library. I suggest you remove the line:
<script src="go.js"></script>
EDIT: In addition, there are some typos that I missed before when just reading your code. This actually works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/gojs/release/go-debug.js"></script>
<script>
function init() {
var $ = go.GraphObject.make;
var myDiagram = $(go.Diagram, "decisionTree");
var nodeDataArray = [
{ key: "Alpha" },
{ key: "Beta" }
];
var linkDataArray = [
{ to: "Beta", from: "Alpha" }
];
myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray)
}
</script>
</head>
<body onload="init()">
<div id="decisionTree" style="width:300px; height:300px; border:1px solid black;"></div>
</body>
</html>

Categories