Am just starting with Vue.js and ui development, and I am trying to make a very simple vue.js call. However, when I am launching my html page using liveserver on Visual Studio Code no JavaScript function is getting called from app.js. I cant figure out what is wrong with the code.
Can someone please advise?
Vue included in HTML-
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue Basics</title>
<link
href="https://fonts.googleapis.com/css2?family=Jost:wght#400;700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<script src="https://unpkg.com/vue#next" defer></script>
<script src="app.js" defer></script>
app.js code -
function getRandomValue(min, max){
return Math.floor(Math.random() * (max - min)) + min;}
const app = Vue.createApp({
data(){
return{
playerHealth:100,
monsterHealth:100
};
},
methods:{
attackMonster(){
console.log('attack called')
const attackValue = getRandomValue(5,12);
this.monsterHealth = this.monsterHealth - attackValue;
this.attackPlayer()
},
attackPlayer(){
console.log('attack Player called')
const attackValue = getRandomValue(8,15);
this.playerHealth = this.playerHealth - attackValue;
}
}
});
You need to mount your app to a <div> tag, for example:
In your html:
<div id="app"></div>
In app.js:
const vm = app.mount('#app')
Here is the detailed explanation from Vue.js documentation:
https://v3.vuejs.org/guide/instance.html#creating-an-application-instance
You have defined methods attackMonster and attackPlayer but you didn't call them. You can use created() to call them or you can also use mounted() (if you need to access DOM).
created () {
this.attackMonster();
}
Also you need to mount Vue app to HTML.
const app = Vue.createApp({
/** the rest of your vue app */
/** the rest of your vue app */
created () {
this.attackMonster();
}
})
const vm = app.mount('#app');
html
<body>
<div id="app">
<p>playerHealth: {{ playerHealth }}</p>
<p>monsterHealth: {{ monsterHealth }}</p>
</div>
</body>
Please check the path in your script tag
<script src="/path/to/app.js" defer></script>
Related
This my code HTML file
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<script src="../node_modules/rxjs/bundles/rxjs.umd.min.js"></script>
<script src="./Test.js"></script>
</body>
</html>
This my code Js file
const stream = Rx.Observable.create(...);
When I want to use Rx I get Error.
Uncaught ReferenceError: Rx is not defined
I can’t understand what the problem is.
In RxJs 6 the object is called rxjs
const stream = rxjs.Observable.create(...);
or
const { Observable } = rxjs;
const stream = Observable.create(...);
If you are using npm then you need to import the parts you need as the main thing about RxJs 6 over 5 is that it is tree shakeable
import { Observable } from 'rxjs';
const stream = Observable.create(...);
I am using modern Javascript MyClass.js
export default class MyClass {
constructor(x) {
this.val=x? x: "Hello!"
console.log("MyClass:",x)
}
}
at my http://localhost/myfolder/mypage.htm, with the source below,
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel='shortcut icon' type='image/x-icon' href='./favicon.ico' />
<script type="module" src="./MyClass.js"></script>
<script>
'use strict';
document.addEventListener('DOMContentLoaded', function(){
alert(123)
let x = new MyClass(11);
}, false); //ONLOAD
</script>
</head>
<body> <p>Hello1!</p> </body>
</html>
Why console say "Uncaught ReferenceError: MyClass is not defined"?
PS: this question is a complement for this other about using ES6+ with browser+NodeJs.
NOTE: using UBUNTU ith Apache's Localhost... Some problem with myfolder a symbolic link to real folder? at /var/www/html I used ln -s /home/user/myRealFolder/site myfolder
you need to import the module before using it
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<script type="module" src="./MyClass.js"></script>
<script type="module" id="m1">
// script module is an "island", not need onload.
'use strict';
import MyClass from './MyClass.js';
let x = new MyClass(11); // we can use here...
console.log("debug m1:", x) // working fine!
window.MyClassRef = MyClass; // "globalizing" class
window.xRef = x // "globalizing" instance
</script>
<script> // NON-module global script
document.addEventListener('DOMContentLoaded',function(){
// only works after all modules loaded:
console.log("debug:", window.xRef) // working fine!
let x = new window.MyClassRef(22); // using class also here,
console.log("debug:", x) // working fine!
}, false); //ONLOAD
</script>
</head>
<body> <p>Hello1!</p> </body>
</html>
There are two ways to use an imported class:
at module scope (script m1): you can use new MyClass(), and can "globalize" instances (e.g. xRef) or the costructor's class (MyClassRef).
at global scope: to work together other libraries or with main script, use a global reference, e.g. new window.MyClassRef().
All this solution relies upon "static import"...
Optional dynamic import
You can use also import with ordinary default <script> (no type="module"), and no "onload", using this solution, instead the last script:
<script>
'use strict';
import('./MyClass.js').then(({default: MyClass}) => {
alert(123) // async block
let x = new MyClass(11);
});
</script>
See dynamic import.
I'm trying to use the tensorflow.js API, and I want to import a saved python tensorflow model. I'm using this github library for the conversion. I've got these script imports in my html file:
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#0.8.0"></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs-core"></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs-converter"></script>
Then when I do this:
const model = await loadFrozenModel(MODEL_URL, WEIGHTS_URL);
It says the class "loadFrozenModel is not defined".
In the github page it said to import using these:
import * as tfc from '#tensorflow/tfjs-core';
import {loadFrozenModel} from '#tensorflow/tfjs-converter';
When I do that, it gives:
" Uncaught SyntaxError: Unexpected token * "
and
" Uncaught SyntaxError: Unexpected token { "
respectively. This error is even given when I install libraries using npm. Note: I'm using windows 10 and installed a third party npm.
This are the two files in entirety if I missed out some important details:
index.html :
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#0.8.0"></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs-core"></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs-converter"></script>
</head>
<body>
Tiny TFJS example.<hr>
<div id="micro_out_div"></div>
<script src="index.js"> </script>
</body>
index.js :
async function myFirstTfjs() {
const MODEL_URL = "PATH/TO/tensorflowjs_model.pb";
const WEIGHTS_URL = 'PATH/TO/weights_manifest.json';
const model = await loadFrozenModel(MODEL_URL, WEIGHTS_URL);
const feed = {
'op_to_restore': tf.tensor1d([0, 0, 0, 0])
};
document.getElementById('micro_out_div').innerText += model.execute(feed);
}
myFirstTfjs();
By the time now, the problem is solved.
here's the final one.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#0.11.2"> </script>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs-converter"></script>
<script type="text/javascript">
const MODEL_URL = 'http://localhost:8000/tensorflowjs_model.pb';
const WEIGHTS_URL = 'http://localhost:8000/weights_manifest.json';
const model = tf.loadFrozenModel(MODEL_URL, WEIGHTS_URL);
console.log("model loaded");
</script>
</head>
<body>
</body>
</html>
Do remember to add this extension to disable CORS warning
I think you are not seeing loadFrozenModel because the script is being loaded as a module. Also, #tensorflow/tfjs includes #tensorflow/tfjs-core, so you won't need to import both.
<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#0.9.0></script>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs-converter"></script>
</head>
<body>
Tiny TFJS example.<hr>
<div id="micro_out_div"></div>
</body>
<script src="index.js"> </script>
</html>
If you are importing via script tags then you need to add tf_converter, as follows:
const model = await tf_converter.loadFrozenModel(MODEL_URL, WEIGHTS_URL);
I'm, working on server-side rendering in a React app and I have the following JavaScript code. My <FullPage action={this.handler}/> component has an action property that is set to a function. When that function gets called, I want to set a variable (or even some state) in this component here. I can't figure out how to declare handler
export default (req) => {
var myVar =
<Router location={req.path} context={{}}>
<FullPage action={this.handler}/>
</Router>
const content = renderToString(
myVar
);
return `
<html>
<head>
<link rel="stylesheet" href="App.css">
</head>
<body>
<div id="root">${content}</div>
<script src="bundleclient.js"></script>
</body>
</html>
`;
};
I'm playing around with ReactJS. I have defined three components, which are nested:
UserProfile.jsx
var React = require('react');
var UserProfile = React.createClass({
getInitialState: function() {
return {
username: "zuck"
};
},
render: function() {
return (
<UserProfile>
<ProfileImage username={this.props.username}/>
<ProfileLink username={this.props.username}/>
</UserProfile>
);
}
});
React.render(<UserProfile username="zuck"/>, document.body);
module.exports = UserProfile;
ProfileLink.jsx
var React = require('react');
var ProfileLink = React.createClass({
render: function() {
return (
{this.props.username}
);
}
});
module.exports = ProfileLink;
ProfileImage.jsx
var React = require('react');
var ProfileImage = React.createClass({
render: function() {
return (
<img src="//graph.facebook.com/{this.props.username}/picture"/>
);
}
});
module.exports = ProfileImage;
My html file basically only includes the three jsx files (btw, is there a way to bundle all these into a single request during development?)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React FB Link</title>
</head>
<body>
<script type="text/javascript" src="UserProfile.jsx"></script>
<script type="text/javascript" src="ProfileLink.jsx"></script>
<script type="text/javascript" src="ProfileImage.jsx"></script>
</body>
</html>
I'm using beefy to handle and serve the JSX files, using beefy *.jsx 8000 -- -t reactify.
The resulting files are (in truncated form):
UserProfile.jsx
ProfileLink.jsx
ProfileImage.jsx
Loading the html page results in an error:
Uncaught ReferenceError: ProfileImage is not defined
with reference to line 15 in UserProfile.jsx:
React.createElement(ProfileImage, {username: this.props.username}),
You might need to load ProfileImage.jsx and ProfileLink.jsx before your UserProfile.jsx since right now the page is parsing Userprofile.jsx first and it doesn't know what ProfileImage mean (because you haven't loaded it yet)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React FB Link</title>
</head>
<body>
<script type="text/javascript" src="ProfileLink.jsx"></script>
<script type="text/javascript" src="ProfileImage.jsx"></script>
<script type="text/javascript" src="UserProfile.jsx"></script>
</body>
</html>
You can use any module bundler to bundle up your files (Browserify, Gulp, Webpack) into one single file as entry point