1

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;
     }
}
 });
1
  • I can see you've defined methods, but I can't see you calling any of them. Try doing something on the created() hook. Commented Nov 16, 2020 at 16:09

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

Please check the path in your script tag

<script src="/path/to/app.js" defer></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.