Vue.js 2 not triggering defined method function on click event

Seems like a simple task, but it's not working for me. Maybe because I'm new to VueJS. I downloaded this repository: https://github.com/creotip/vue-particles. I want to use this style to create an under construction page.

The issue is that I need to create a hamburger menu icon in the top right corner, which when clicked should call a method to show and hide a div (very basic stuff). I've followed Vue JS tutorials and advice from Stack Overflow, but my template doesn't seem to be communicating with the method.

Every time I click on the hamburger button, I get an error "_vm.hello is not a function". What am I doing wrong? Please refer to the screenshot attached. There must be a simple solution to this problem.

This is how my code looks:

app.vue

<template>
  <div id="app">
    <div class="wrap-banner">
      <div class="button_container" @click="hello()">
        <span class="top"></span>
        <span class="middle"></span>
        <span class="bottom"></span>
      </div>
  </div>
</template>

main.js

import Vue from 'vue'
import App from './App'
import Home from './components/home'

Vue.use(Home)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
  methods: {
    hello: function() {
        alert('hello')
    }
  }
})

Screenshot

https://i.sstatic.net/INyRQ.jpg

Answer №1

Ensure to relocate the hello function to the App.vue file

App.vue

   <template>
  <div id="app">
   <div class="wrap-banner">
      <div class="button_container" @click="hello">
        Click Here
        <span class="top"></span>
        <span class="middle"></span>
        <span class="bottom"></span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {};
  },
  methods: {
    hello: function() {
      alert("Hello there!");
    }
  }
};
</script>

main.js

import Vue from "vue";
import App from "./App";

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})

To see a live demonstration, visit https://codesandbox.io/s/8y5yzv00nj

Answer №2

Understanding Vue File Structure

It's important to note that a Vue file consists of three main components: HTML, JavaScript, and CSS. To ensure that the file is properly interpreted by the browser, it must be processed using a compiler such as Babel. Check out Vue Single File Components for detailed information.

Efficient Solution

The vue-cli tool provides a convenient starter template with preconfigured Babel and Webpack settings. Simply create a Vue project and customize the template according to your requirements.

  1. Download Vue-CLI
  2. Run vue create my-project
  3. Execute npm run dev

Alternative Approach

If you prefer not to use a compiler, you can set up your Vue file like this:

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    hello: function() {
        alert('hello')
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <button @click="hello()">Click me</button>
</div>

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

Is there a way to activate Toast notification before the window's onbeforeunload event?

Here's a snippet of JavaScript that I have been working on. It currently pops up an alert when someone tries to leave a form without completing it. However, my goal is to display a Toast notification first with some additional information informing th ...

Can someone recommend a design pattern to implement in React?

I have encountered a challenge while working with over a thousand svg elements. Whenever I try to remove, update, or select a single element, it consumes a significant amount of time. The issue lies in the fact that when I modify or delete a specific svg e ...

The power of VueRouter lies in its ability to leverage metadata

According to the VueRouter documentation, you can include meta fields and globally restrict routes based on their specified values. However, upon trying to implement this feature based on the guidelines provided, an error occurred: ReferenceError: record ...

verifying the string's value within the ng-if condition

Currently, I am trying to assess the value of a property within an object and comparing it with string data. <div ng-if="results.dataType === 'textTable'"> The content is meant for display in a table. </div> At present, all d ...

How to Retrieve a Remote File in Angular using $http.get() with OAuth Authentication

I have a unique situation where my users possess private files that require downloads by authenticated users. The server I am using initially downloads a file from S3 utilizing its own set of S3 app_id and secret_token credentials. Once the file has been d ...

What is the best way to send the selected option from a dropdown to a button click function within the controller?

I need to pass the selected value from a user's country selection dropdown to the ng-click="saveChanges()" function on the submit button. Is there a correct method for achieving this? I want to be able to access the user's selection from the dro ...

How can WebRTC be used to minimize latency between devices transmitting video streams?

Apologies for not including any code, but I am currently focused on expanding my knowledge of latency and webRTC. What methods are most effective in minimizing the latency between multiple devices sharing a video stream? Alternatively, how can we reduce l ...

Is it possible to keep my JavaScript scripts running continuously within my HTML code?

I recently set up a JavaScript file that continuously queries an API for updates. It's currently linked to my index.html, but I'm looking for a way to keep it live and running 24/7 without requiring the browser to be open. Any suggestions on how ...

What is the best method for efficiently adding a new element to an array in JavaScript?

Here's a question for you: When it comes to adding elements at the end of a JavaScript array, is there any speed or optimization advantage to using one form over the other? Or does it simply come down to personal preference? (1) pageData[pageData.len ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

Having trouble with your jQuery animation on a div?

Check out this jsFiddle example: http://jsfiddle.net/uM68j/ After clicking on one of the links in the demo, the bar is supposed to smoothly slide to the top. However, instead of animating, it immediately jumps to the top. How can I modify the code to ac ...

What could be the reason for my button to update only at the completion of the "each" loop?

Is there a way to update the button text before the loop, so that users can receive feedback while it's running? Currently, the text only updates after the loop has completed. In my scenario, the button displays "Updating please wait..." after the lo ...

Tips for transferring a jQuery array to PHP

I am encountering an issue when trying to send a jQuery array to PHP. Initially, I have one form in HTML and upon clicking 'add', I end up with two forms. Afterwards, I input data into the form which is then stored in a jQuery array. However, I a ...

Dealing with distinct form actions for 'new' and 'edit' in Rails using simple_form, remote_true, and custom controller

I've been following a tutorial on how Ajax works with Ruby on Rails. However, I decided to take a slightly different approach. After setting up a scaffold for 'tasks' (including the controller, model, and views), I created a new controller c ...

Explore the input from multiple users to uncover the word that appears most frequently among them

Hey there (brand new to JavaScript), I am working on a simple program that requires input from multiple users through prompt pop-ups. For example: <script type="text/javascript> var userInput = prompt("Enter your input:"); </script> It&ap ...

Can someone explain why this error code 500 is showing up in my React Native development server's response?

An error occurred: TypeError: Cannot read property 'reduce' of undefined at resolveDependencies (G:\React-Native\Native\chatmat\node_modules\metro\src\DeltaBundler\traverseDependencies.js:411:33) at process ...

Access the JSON file, make changes to a specific value, and then save the

In my JSON data file, I have the following information: [ { "key" : "test1", "desc": "desc1" }, { "key" : "test2", "desc": "desc2" }, ] I have written a script to retrieve this data from the file using AJAX and display it in an HT ...

Can we rely on JavaScript to ensure that iterating over the fields of the same object twice will always follow the same order?

When using a for .. in loop to iterate over the members of an object, the order of enumeration is determined by the implementation. However, if the object remains unchanged, is it guaranteed that iterating over it twice in the same browser during the same ...

elasticsearch query for deletion only returns documents that are not found

I have been attempting to use the https://www.npmjs.com/package/elasticsearch-deletebyquery package to delete documents using a query. However, I keep receiving a "Not found" error. Here is my code snippet: client.deleteByQuery({ index: index, type: t ...

Visibility issue with CKEditor5 in VueJS

I am facing a challenge with creating a component that displays CKEditor allowing me to write Markdown content. Despite the presence of HTML code in the DOM, the CKEditor itself is not visible on the frontend: <div style="display: none;">& ...