Error message: "The property or method you are trying to access is not defined

I had no issues with my app until I added the JavaScript, now I'm getting constant errors in the console.

One of the errors I see is:

Property or method "show" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

And another error is:

TypeError: _vm.show is not a function
  at click App.vue?d98c:25
  at HTMLButtonElement.invoker vue.esm.js?efeb:1906

Goal: When clicking on "loginBtn", an alert should say "click".


This is my code:

// app.vue script 
export default {
  name: 'app'
}

var show = new Vue({
  el: '#loginBtn',
  data: {
    n: 0
  },
  methods: {
    show: function(event) {
      targetId = event.currentTarget.id;
      alert('click')
    }
  }
})

<!-- the button -->
<template>
  <div>
    <button v-on:click="show($event)" id="loginBtn">Login</button>
  </div>
</template>

Answer №1

If you're working with a Single-File Component (a file with a .vue extension), you are using a file format designed for Vue component definitions, which is utilized by vue-loader.

Within the .vue file, the script section (found inside the <script> tag) should contain an object that specifies the Vue instance's definition.

The official documentation states:

The script must export a Vue.js component options object. While exporting an extended constructor created by Vue.extend() is acceptable, it is preferable to use a plain object.


Currently, only the { name: 'app' } object is being exported, causing Vue to be unable to locate the show method.

Your <script> section should resemble the following structure:

<script>
  export default {
    name: 'app',
    data() {
      return { n: 0 }
    },
    methods: {
      show: function(event) {
        targetId = event.currentTarget.id;
        alert('click')
      }
    }
  }
</script>

It's important to note that the data property within the exported object should be a function that returns the data properties. For more information, refer to the "Why does data need to be a function" section on Vue's Common Beginner Gotchas page.

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

Getting Started with Cloudinary Image Upload using Nuxt.js

I'm currently facing an issue while attempting to upload an image to cloudinary from the client side. Even though I have created a Form Data and tried to pass it, it seems to be coming back empty. Here is the HTML code snippet: <div class="my ...

What is the best way to connect click events with ExtJS template elements?

Is there a way to assign a click event to each link tag without directly embedding onclick=.... in the XTemplate code? new Ext.XTemplate( '<ul>', '<tpl for="."><li><a href="#{anchor}">{text}</a></li& ...

Switching icon with jQuery upon clicking

I'm just starting to learn jQuery and I'm working on changing the font icon class when clicked to display a drop down. Right now, it changes the icon and drops down the content as expected. However, I'm facing an issue where I want the icon ...

What is the best way to initiate a dialogue (updating component state) using Vue Router?

I am looking to enhance page state management using vue router. For instance: / should navigate to the home page. /login will keep the user on the home page while triggering a dialog with the login form. /register will also trigger the dialog, but this t ...

What is the best way to retrieve the previous state of a file field in React?

Currently, I am working on implementing an on-change handler for an audio file in a component. The goal is to load the previous state of the file when the user changes it and records the new path. Specifically, when the user enters the component, the file ...

Steps for saving both checked and unchecked checkbox values in Firebase

I have a set of objects that I am using as initial data in my Ionic 3 application: public interests = [ { name: 'Travel', checked: false }, { name: 'Animals', checked: false }, { name: 'Theatre', checked: false ...

What is the purpose of implementing asynchronous loading for JavaScript in my webpack setup?

I am facing difficulties with handling unusual codes. I am trying to add some query parameters using $.ajaxPrefilter in all jQuery ajax requests. I came across the following code snippet which seems to ensure synchronous loading order, but in my entry.js ...

Guide on creating a custom type for an object utilizing an enum framework

Enumerating my shortcuts: export enum Hotkey { MARK_IN = 'markIn', MARK_OUT = 'markOut', GO_TO_MARK_IN = 'goToMarkIn', GO_TO_MARK_OUT = 'goToMarkOut' } I am now looking to define a type for a JSON ob ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

Leveraging various libraries in React

My query revolves around a React application where I have integrated Material UI for only two components. Despite installing the entire Material UI library, will this lead to an increased bundle size for my application? Or does the build process only inc ...

Is it possible to notify the user directly from the route or middleware?

In my current setup, I am utilizing a route to verify the validity of a token. If the token is invalid, I redirect the user to the login page. I am considering two options for notifying users when they are being logged out: either through an alert message ...

The custom stylesheet added to index.html is not taking precedence over the Bootstrap 5 styles applied through NPM

In my Vue 2 project, I encountered an issue with Bootstrap 5.3 when installed via NPM. My custom CSS stylesheet in the index.html file was not able to override Bootstrap's CSS. Interestingly, I faced no problems when using Bootstrap from a CDN. Addit ...

The default locale for momentJS is set to zh-tw and I'm having trouble changing it

Currently, I am incorporating the momentJS library into my Angular application by pulling it from a CDN: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script> Although the default locale should be Engli ...

Guide for Uploading, presenting, and storing images in a database column with the help of jQuery scripting language

What is the best method for uploading, displaying, and saving an image in a database using jQuery JavaScript with API calls? I am working with four fields in my database: 1. File ID 2. Filename 3. Filesize 4. Filepath ...

What is the best way to retrieve a {collection object} from a JavaScript map?

My application utilizes a third-party library that returns the map in the following format: public sids: Map<SocketId, Set<Room>> = new Map(); When I try to access it using the code below: io.of("/").adapter.sids.forEach(function(va ...

Leveraging vuex in conjunction with typescript allows for efficient management of state in namespace modules,

I am currently integrating vuex with typescript and namespaces module in my project. Within this setup, I have two distinct modules: "UserProfile" and "Trips". So far, everything is functioning smoothly within the confines of each module. However, I have ...

Chrome tab freezes when scrolling with the mouse

Working on a particularly interesting bug, I've managed to replicate it using a fiddle. The issue arises when the middle mouse button is clicked over the div element containing text, causing the pointer to become stuck. Is this possibly a browser bug ...

Achieving dynamic key assignment when updating with mongoose in NodeJS and Express

With a multitude of keys requiring updates from a single function, I am seeking guidance on how to dynamically set the key for updating. static async updateProfile(req, res, next) { const userId = req.body.userId; // The key requiring an update ...

Swapping out the default JavaScript random number generator for my custom JSON-based solution

I've been working on creating a D3 graph to display my data. After following a tutorial, I arrived at this particular piece of code: // 8. An array of objects of length N. Each object has key -> value pair, the key being "y" and the value is a r ...

Which specific indexOf method is the most appropriate for my use case?

While exploring a codebase, I came across this code snippet that adds the indexOf function: if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments ...