What's preventing the bind click event from working properly?

I have a unique Vue application setup like this:

index.html structure:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>vuejs-test01</title>

    <link href="./src/assets/styles/style.css" type="text/css" rel="stylesheet"  >
  </head>
  <body>
    <div id="app">
      <div id="bag"></div>

      <div id="bag-helth">
        <div :style="{ width:helth + '%' }"></div>
      </div>

      <div id="control">
        <button @click="punch" v-show="!ended">click</button>
        <button @click="restart">restart</button>
      </div>
    </div>

  </body>
</html>

main.js code, rendering the App.vue file in the render function:

import Vue from 'vue'
import App from './App.vue'

import './assets/styles/global.styl'

new Vue({
  el: '#app',
  render: h => h(App),   
})

The styles defined in my style.css file are as follows:

#bag {
  width: 200px;
  height: 500px;
  margin: 0 auto;
  background: url(../imgs/02.png) center no-repeat;
  background-size: 80%;
}

#bag-helth {
  width: 200px;
  border: 2px #000 solid;
  margin: 0 auto 20px auto;
}

#bag-helth div {
  height: 20px;
  background: crimson;
}

#control {
  width: 200px;
  margin: 0 auto;
  text-align: center;
}

The code for my Vue.app, with the export default section included:

<template>

</template>

<script>

  export default {
    data: {
      helth: 100,
      ended: false,
    },
    methods: {
      punch: function () {
        this.helth -= 10

        if (this.helth <= 0) {
          this.ended = true
        }
      },
      restart: function () {
        this.helth = 100
        this.ended = false
      }
    }
  }
</script>

<style scoped>

</style>

Upon testing in the browser, I noticed there is no response when clicking the buttons.


EDIT-1

After investigating, I discovered that by adding the value {{ helth }} within the #bag div in index.html:

<div id="app">
  <div id="bag">{{ helth }}</div>
...

The template does not interpret the data correctly:

https://i.sstatic.net/6INqC.jpg

Answer №1

Insert your HTML codes into the App.vue file within the template tags instead of placing them in the index.html. This way, your index.html will appear as follows:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8>
 <title>vuejs-test01</title>

 <link href="./src/assets/styles/style.css" type="text/css" rel="stylesheet"  >
</head>
<body>
 <div id="app"></div>
 <script src="/dist/build.js"></script>
</body>
</html>

Your App.vue component should be structured like this:

<template>
 <div id="app">
    <div id="health">{{ health }}</div>

   <div id="health-bar">
     <div :style="{ width: health + '%' }"></div>
   </div>

   <div id="control">
     <button @click="punch" v-show="!ended">Click</button>
     <button @click="restart">Restart</button>
   </div>
 </div>
</template>

<script>
 export default {
   data() {
     return {
       health: 100,
       ended: false,
     };
   },
   methods: {
     punch() {
       this.health -= 10;

       if (this.health <= 0) {
         this.ended = true;
       }
     },
     restart() {
       this.health = 100;
       this.ended = false;
     },
   },
 };
</script>

<style scoped>

</style>

Answer №2

There are a few errors in your project that need to be addressed:

  1. The template code should be placed in your App.vue:


      <div id="bag-helth">
        <div :style="{ width:helth + '%' }"></div>
      </div>
    
      <div id="control">
        <button @click="punch" v-show="!ended">click</button>
        <button @click="restart">restart</button>
      </div>
    </div>
    

In your index.html, make sure to include an empty div as <div id="app"></div> and the build.js file as shown below:

<body>
  <div id="app"></div>
  <script src="/dist/build.js"></script>
</body>

In the main.js, you can then render the App.vue component inside the index.html's <div id="app"></app>:

new Vue({
  el: '#app',
  render: h => h(App)  
})
  1. Remember, the App.vue is a component, not a Vue instance - the data should be inside a function:

    export default {
      data: function() {
        return {
          helth: 100,
          ended: false
        }
      },
    ...
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the ng-show attribute in a different controller

I am attempting to toggle the visibility of a div using ng-show. Specifically, I have a navbar that should only be displayed in certain views. I have one controller managing the behavior of this div, and another controller where I want to manipulate the v ...

Oops! There seems to be a problem with the Node.js App. The MongooseError is indicating that the parameter `uri` in the `openUri()` function should be a string,

I've encountered an issue with my Next.js app involving MongoDB that I've been struggling to resolve. Hoping someone here can provide some insight and help me out. This is quite crucial for my project. First, I'll share the code from my serv ...

Tips for extracting unique values from two arrays and returning them in a new array using JavaScript

Hello, I need assistance with combining two arrays. Array a contains [1,2,3] and array b contains [2,5]. I would like the result array to only include elements that are unique between the two arrays, such as [5]. Can you please provide guidance on how to ...

Comparing Node.js and Node on Ubuntu 12.04

After following the instructions on this website, I successfully installed nodejs on my ubuntu system. However, when I type node --version in the terminal, I get an error message saying: -bash: /usr/sbin/node: No such file or directory Oddly enough, ...

Measuring JSON data with PHP through asynchronous requests

Looking to retrieve a specific count from a json dataset. Here is an example json format: { "tickets": [ { "url": "https://asd.zendesk.com/api/v2/tickets/1.json", "id": 1, "external_id": null, "via": { "channel": "sa ...

Accessing S3 bucket contents in Angular using Observables

Looking for guidance on structuring a service method in Angular4 to create an s3.listObjects call and return the contents of an S3 bucket as an Observable. Here is my current attempt, unfortunately not yielding successful results: public retrieveFilesFro ...

Synchronizing the call of various views in an Angular application

I'm currently working on an angular single page application with a specific structure in mind. "app.parent - main parent state" "app.parent.childState - child state" "app.parent.childSatate" includes 4 different named views. My goal is to display so ...

Exploring React Native Networking using react-native-router-flux

Hello everyone, I have a quick query. I am looking to assign each Button to a different page. import React, { Component } from 'react'; import { ActivityIndicator, FlatList, Text, View, TouchableOpacity } from 'react-native'; export ...

Guide on setting up an Express application to control LED light strips with a Raspberry Pi3

After setting up a node server on my Raspberry Pi to control an Adafruit Dotstar light strip, I encountered a problem. The sequence of colors on the light strip is triggered by an HTTP request to localhost:8000/fade, causing the server to run fade.js endle ...

I'm having trouble retrieving the precise coordinates of a mouse click. Can anyone help troubleshoot my code?

When attempting to display something at the exact place where a mouse click occurs, I utilized the following code snippet: $('#my-graph').mousedown(function(evt){ // show object at: var x= evt.screenX, y=evt.screenY; //or sho ...

What could be causing the absence of console.log output in my Netlify function logs?

I am facing an issue with my Netlify function that is scheduled to run every minute using the @netlify/functions package. The function makes API calls and logs the response, but I cannot see any output from the console.log statement in the Netlify function ...

Vue is encountering difficulties resolving the index.vue file located in the parent directory

Having trouble importing a component from the path folder, I keep encountering an error message stating "Cannot find module './components/layout/Navbar'. Vetur(2307)". This is how I am attempting to import the component: import Navbar from "./c ...

I am experiencing difficulty transitioning the view in React Native from a side position to an inward direction

Currently tackling a design project and encountering a roadblock in achieving a specific curved effect. Here are two images for reference: The Desired Design: My Current Progress: The basic structure is in place, but hitting a wall when attempting to cu ...

Issue with WebRTC, socket.io, and node.js: Unable to access the property 'emit' as it is undefined

Currently, I am in the process of creating a webrtc video app. Within the client code section, the following lines are present: getUserMedia(constraints, handlemedia, errorhandle); constraints = {video: true}; function handlemedia(stream){ //other act ...

Updating the value of an Angular select on change is not being reflected

If the select element is changed, the value should be set to something different from what was selected. There's a feature in place that only allows 4 item types to be selected at a time; if more than 4 are chosen, the value reverts back to its origin ...

`How can I refresh the URL in Vue with new query parameters, even if it is the same page?`

I am facing an issue with my website that has a search bar. When a user searches and hits enter, I want the page to reload with the new query parameters in the URL. The challenge here is that if the user is already on the same page, although the query par ...

Developing a react native library (create-react-native-library) incorporating a distinct react-native version within its designated Example directory

I'm looking to develop a React Native library, but the testing folder (example folder) it contains the latest version of React Native. However, I specifically need version 0.72.6 in the example folder. Is there a command for this? Current command: np ...

Tips for resizing the MUI-card on a smaller screen

Is there a way to adjust the width of the card on small screen sizes? It appears too small. You can view my recreation on codesandbox here: https://codesandbox.io/s/nameless-darkness-d8tsq9?file=/demo.js The width seems inadequate for this particular scr ...

Comparing Redux with passing state down to components as props from the top level of the application

With limited experience in react-redux, I am currently working on a smaller web-based application intended for around 100 users. At this time, I have opted not to use redux due to concerns about its complexity for such a small project. Instead, I have been ...

What is the reason border property does not transition effectively?

I am trying to remove the border property after a certain period of time (1 second) and make it smooth. Here is what I have attempted: var elem = $('div').css({'border-top':'6px solid #FC9A24', 'border-le ...