Vue alert: The instance does not have a defined "hp" property or method, but it is referenced during rendering

Below is the code snippet that I am currently working with:

var example1;
var hp = ["p"];

document.addEventListener("DOMContentLoaded", function(event) {
  hp = ["x"];
  example1 = new Vue({
    el: '#example-1',
    data: {
      iLoveMyself: window.hp
    },
    
    watch: {
      iLoveMyself: {
        deep: true,
        immediate: true,
        handler (val, oldVal) {
          console.log("yeeeh")
        }
      }
    }
  })
});

I've attempted various solutions which resulted in the following console error:

vue.js:634 [Vue warn]: Property or method "hp" 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. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

When checking the value using a Chrome plugin for VueJs, the data set appears as follows:

iLoveMyself:Array[1]
0:"x"

Everything seems fine up to this point, however, when attempting to update hp using the following commands:

hp.push("y");
hp.pop();
hp = "ZEBRA";

No response is received.

What could be the issue that I'm failing to grasp?

Appreciate any help in advance!

Edit: It turns out, after all, that my HTML structure is crucial :(

<div id="example-1">
  <div v-for="ev in hp" :key="ev.beavus">
    {{ ev.beavus }}
  </div>
</div>

Answer №1

Here is a more idiomatic Vue approach to the code you provided:

new Vue({
  el: '#example-1',

  data: {
    favoriteFruits: [{apple: "red"}]
  },

  watch: {
    favoriteFruits: {
      deep: true,
      immediate: true,
      handler (val, oldVal) {
        console.log("fruit added!")
      }
    }
  },
  
  methods: {
    add () {
      this.favoriteFruits.push({apple: "yellow"})
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="example-1">
  <div v-for="fruit in favoriteFruits" :key="fruit.apple">
    {{ fruit.apple }}
  </div>
  <button @click="add">Add</button>
</div>
  

I have eliminated global variables and instead utilized an instance property named favoriteFruits to store the array. Adding new fruit data to the array will trigger the watch function and update the DOM with the additional information.

Answer №2

It is recommended to:

<div id="example-1">
  <div v-for="event in selfLoveArray" :key="event.id">
    {{ event.name }}
  </div>
</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

What is the process for incorporating Angular.js with a live messaging platform such as Pusher or PubNub?

Can Pusher or PubNub be implemented as an Angular service? Anyone have any examples of code for this kind of integration? ...

Is the term "filter" considered a reserved keyword in Angular, Javascript, or ASP.Net MVC?

When using angularJS to call an ASP.Net MVC controller from a service, I encountered an issue with one of the parameters: $http({ method: "get", url: "ControllerMethod", params: { param1: param1Value, pageNumber: pageNumber, ...

Modify the divs in two separate occasions when submitting different forms

Within my form, I have radio buttons located inside div1, a captcha code to be solved in div2, and additional content in div3. My goal is to have div1 replaced by div2 when a radio button is checked and submitted. Then, after completing the captcha in div2 ...

Can regex matching characters be made easier to understand?

I am working on creating an ECMAScript (JavaScript) flavored regex to evaluate the complexity of my password based on specific criteria: Characters Used Password Strength Length ABC abc 123 #$& WEAK ... 1 x ...

JavaScript Indexed Array Names: Managing Arrays with Indices

I have a collection of arrays named "list0" through "list7" which have been explicitly defined. My goal is to include each of these arrays as elements in an existing array, creating a 2D array of these defined arrays. How can I reference each 'list&a ...

Is there a way to dynamically alter the background style of a div by clicking on it multiple times using Javascript?

I am attempting to create a calendar where each day changes its background color between blue and green when clicked, using JavaScript and CSS. It should function similar to a toggle feature. The default color is blue, and I have successfully made the days ...

One way to send image data from the front end to the back end using AJAX

Client-Side JavaScript: var userInfo = { 'username': $('#addUser fieldset input#inputUserName').val(), 'email': $('#addUser fieldset input#inputUserEmail').val(), 'fullname': $('#addUser f ...

JavaScript for Dynamic Scaling Animations

I am currently working on animating an SVG button and I am trying to incorporate the transform property with a fadeout using opacity attributes in Javascript. This is how I have attempted to write the code: (Starting with opacity 0 and scale 0) (I am awa ...

Storing user information in Angular after login and implementing JWT authentication

Is it advisable to save any user information other than JWT in local storage or cookies after a successful login? (The user profile object is already saved and encrypted in the JWT payload sub-part.) I need the user profile object ready before initializing ...

Guide to organizing files with custom directory layout in NodeJS

Imagine having multiple files spread across various folders. /parentDir/ |__dirA/ |__file1 |__file2 |... |__dirB/ |__file3 |... |... You want to consolidate them into an archive, with the option of using something like ...

Stop displaying AJAX requests in the console tab of Firebug, similar to how Twitter does it

I'm looking for a way to prevent my AJAX calls from being logged in Firebug's Console tab, similar to how Twitter does it. When using Twitter search, you'll see a live update feed showing "5 tweets since you searched." Twitter sends periodic ...

Sending a JavaScript string to a PHP script from a Chrome extension content script

I am currently developing a chrome extension that is designed to extract text data from specific websites when I visit them, and then store this data in a SQL database. The JavaScript code for data extraction is functioning correctly and is able to capture ...

The choice between invoking a function within a route handler or employing a middleware for the task

I am currently exploring a potential difference in coding approaches. Let me illustrate this with an example excerpted from the express documentation: https://expressjs.com/en/guide/using-middleware.html function logOriginalUrl (req, res, next) { console ...

Does the use of 'window.location.replace' in Chrome cause a session to be destroyed in PHP when redirecting to a specified page?

Apologies if the question seems a bit convoluted, but let me explain the scenario. Here is an example of an Ajax function I am working with: $.ajax({ url:"../controllers/xx_register.php", type:"POST", data:send, success: function(resp ...

Is it better to choose AJAX and JQuery for their speed and complexity, or stick with the simplicity of GET requests?

When a user attempts to log in and fails, an error message should be displayed on the page. There are two primary methods that can be used to achieve this: one involves using a form action on the HTML page and handling incorrect login information in the PH ...

React.js implementation of a checkout feature using in-game currency

I am currently working on a game that involves in-game currency, but I'm facing some confusion. It seems like I might be overcomplicating things. In my store, users can purchase items using the gold (max variable) they have. The shopping cart function ...

What is the best way to determine if a page component is using a specific definePageMeta layout?

My application's page layout is now dynamic based on the current user. However, I want to verify if the current page has explicitly defined its layout to prevent it from being overridden by the watchEffect below. (app.vue) <template> <Nuxt ...

How can I add content using HTML or JavaScript?

How can I append a .txt file using HTML or Java without ActiveX prompts getting in the way? It's becoming quite annoying! Is there a simple way to script this task without having to deal with ActiveX? The current script snippet looks something like ...

Encountering unexpected outputs from JSONify

How can I send the result of a Python function back to my JavaScript using AJAX? Currently, I am receiving this response, but I am expecting either "True" or "False." Here is my jQuery code: var test = $.getJSON("/chk_chn", { name: channel_name }); ...

How to access a file stored within a proxy object using Vue.js

I am currently working on sending a file from a vue-page to the server. To achieve this, I have implemented the following: FileFrom component: <template> <div class="FileForm" v-bind:name="name"> <label clas ...