Encountering an error in Vue.js where a "cannot read property of undefined" message is displayed when attempting to use v

While attempting to use v-model on an array item's property, I encountered the error message

"[Vue warn]: Error in render function: 'TypeError: Cannot read property 'viewFood' of undefined'
when loading the page. This resulted in a blank page.

This issue is specific to vue.js version 2.x.

https://codepen.io/jzaun/pen/YxYyJN/

HTML:

<div id="ai-config">
    <div class="info">
      <div class="row">
        <h1>Resource Points</h1>
      </div>
      <div class="row">
        <label>Total:</label>
        <div class="value">
          {{maxResourcePoints}}
        </div>
      </div>
      <div class="row">
        <label>Remaining:</label>
        <div class="value">
          {{maxResourcePoints - usedResourcePoints}}
        </div>
      </div>
    </div>
    <div>
      <table>
        <tr>
          <td></td>
          <td v-for="(option, idx) in options">
            {{option.title}}
          </td>
        </tr>
        <tr v-for="n in directions">
          <td>Direction {{n}}</td>
          <td v-for="option in options">
            <input type="checkbox" v-model="selected[n][option.key]" />
          </td>
        </tr>
      </table>
    </div>
  </div>
  

JavaScript:

new Vue ({
    el: '#ai-config',

    data: {
      maxResourcePoints: 10,
      usedResourcePoints: 0,
      selected: [],

      directions: 8,
      options: [{
        title: 'Food',
        key: 'viewFood',
        cost: 1
      }, {
        title: 'Water',
        key: 'viewWater',
        cost: 1
      }, {
        title: 'Own',
        key: 'viewOwn',
        cost: 1
      }, {
        title: 'Other',
        key: 'viewOther',
        cost: 1
      }]
    },

    methods: {
    },

    created: function () {
      this.selected = [];
      for(i=0; i<8; i++) {
        this.selected.push({});
      }
    }
  });
  

Answer №1

One of the main challenges arises from two key issues.

To begin with, Vue is unable to detect the dynamic addition of a property to an object that has already been included in Vue's data. This becomes evident when you write the following:

v-model="selected[n][option.key]"

In this case, you are introducing a property to the initially empty object created in the create handler. The solution is to instead initialize it with concrete properties (or utilize $set, which may not be applicable in this scenario).

this.selected.push({viewFood: false, viewOwn: false, viewWater: false, viewOther: false});

The second issue (which leads to the error mentioned in your query) involves using a range in the v-for loop where the values start at 1. Therefore,

v-model="selected[n][option.key]"

offends by one due to the fact that JavaScript arrays commence from index 0. In actuality, it should read as follows:

v-model="selected[n - 1][option.key]"

Additionally, there was a minor HTML oversight in the initial pen

<input type="checkbox", v-model="selected[n][option.key]" />

where the comma ought to be omitted.

An updated version of your codepen can be found here.

Answer №2

I have come across the perfect solution for your coding needs. Feel free to explore it here https://codepen.io/spaquet/pen/MvrbLQ

These are the modifications I implemented:

  1. Assigned unique values and IDs to all checkboxes for easy identification of which one is selected.
  2. Eliminated the unnecessary custom function since 'selected' is already defined in the data (it's beneficial to maintain state between reloads).
  3. Incorporated a click event on all checkboxes to demonstrate the selected state during each iteration.

With this update, you can now access the list of selected elements in the format direction-option.key (e.g., 1-viewFood, etc.) within the 'selected' variable.

Answer №3


<tr v-for="n in directions">
directions needs to be an Array, not a Number.

Answer №4

When you start, the 'selected' variable is filled with a group of {} objects. The element selected[n] will initially be an empty object, so consequently selected[n][option.key] is set to null.

By modifying

<input type="checkbox" v-model="selected[n][option.key]" />
to
<input type="checkbox" v-model="option.key">
, I was able to get it to display properly. However, all the checkboxes in a row are linked to the same value - which may not be your desired outcome. This occurs because they all share the same v-model.

If you can provide more information on what you would like this functionality to achieve, I can assist you in resolving the issue. Vue is a powerful framework once you grasp its concepts. Perhaps a visual representation or further elaboration on the expected behavior would be beneficial. Thank you.

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 best way to display index.ejs when the input field is blank?

If the input field is left empty when I click the form button, I want to redirect to "/". After clicking the button, the desired URL should be: http://localhost:3000 Header.ejs <form action="/search" method="GET"> < ...

Discover the Phillips Hue Bridge within the operational web application on a separate network

Utilizing the node-hue-api package on a Node.js/Express server to interact with the Hue API, I've developed an admin section of a website exclusively accessible to me for controlling my Hue lights. The functionality works seamlessly in my local develo ...

Is it advisable to send a response in Express.js or not?

When working with Express.js 4.x, I'm unsure whether to return the response (or next function) or not. So, which is preferred: Option A: app.get('/url', (req, res) => { res.send(200, { message: 'ok' }); }); Or Option B: ...

Issue with child prop not being updated despite changes in parent component

I'm facing a strange issue where altering a child component's prop doesn't trigger a re-render. Here's the scenario: In the parent component, I have: <child :problemProp="proplemPropValue"></child> In the child component, ...

Encountering an issue with MUI 5 where it is unable to access properties of undefined when utilizing makestyles

I recently finished building a react app using MUI-5 and everything was running smoothly. However, I've encountered a strange issue where my app refuses to start and I'm bombarded with multiple MUI errors. These errors started popping up after I ...

Filtering MUI Data Grid by array elements

I am in the process of developing a management system that utilizes three MUIDataGrids. Although only one grid is displayed at a time, users can switch between the three grids by clicking on tabs located above. The setup I have resembles the Facebook Ads ...

`Monitoring and adjusting page view during window resizing in a dynamic website`

Situation: Imagine we are reading content on a responsive page and decide to resize the browser window. As the window narrows, the content above extends down, making the entire page longer. This results in whatever content we were previously viewing bein ...

Shining a component (or persona) however essentially duplicate a distinct term

Is it possible to highlight an element or word, but still copy a different word when hitting ctrl+c? For example, imagine I have an emoji represented by: Original text: :heart: Output in HTML: <span background={...logic here}></span> I am ...

AJAX Image Upload: How to Transfer File Name to Server?

Has anyone successfully uploaded an image to a web server using AJAX, but struggled with passing the file name and path to the PHP script on the server side? Here is the HTML code along with the JavaScript (ImageUpload01.php) that triggers the PHP: Pleas ...

Avoid using the Router with the Search component in React JS

Having trouble rendering my Search component within the main Header component using react-router-dom. I suspect there's an issue with this line of code <Route render={({ history }) => } /> I've been stuck on this for two days now... T ...

Unable to resolve an unresolved issue with a jquery or javascript bug

I am currently facing some issues with my jQuery code in both Firebug and Chrome's developer tools. Any assistance would be greatly appreciated. Kindly make the necessary updates in the provided fiddle. Please follow this link to access the fiddle: ...

Comparison between WAMP and Live server integration with Facebook for connecting applications

I've been facing some challenges while integrating my website with Facebook Connect. I have been following the instructions provided in this guide. When attempting to run the following code from localhost, please note that for security reasons, my ap ...

Nextjs API call ended without a response being sent

I am currently facing a challenge in my NextJS project as my endpoint API does not support multiple calls, and I am looking to implement a data refresh every 3 minutes from the original source. To achieve this, I have integrated an API in NextJS by creati ...

What could be the reason behind the improper display of JavaScript for ID overlay2?

Why is it that when I try to have two overlays with different messages display upon clicking buttons, they both end up showing the same message? Even after changing the ID tag names, the issue persists. Can someone shed some light on what might be causin ...

Capture element in Javascript with screenshot functionality

I've been trying to save an image on my local website, but most of the code examples I find are for C# and Java, which I am struggling to convert to JavaScript. Many of the examples I come across use libraries like Point and IO that are not available ...

I am new to javascript and jquery. I have encountered numerous cases involving audio players

Recently delved into learning javascript and jquery. I managed to create a basic audio player that plays short audio clips. However, I've encountered an issue where clicking the play button on one clip displays stop buttons on all clips instead of on ...

Dynamic sliding box jumps instead of simply fading in/out

My app features both a navigation bar and a sub-navigation bar. Within the sub-navigation bar, users can click on a button that triggers the appearance of another sub-bar while hiding the original one. The new sub-bar should smoothly slide out from behind ...

After modifying environment variables in Vue.js, the application still refers to the previous values

Currently, I am working on a Vue.js project where I have a .env.development file with various VUE_APP_* environment variables. Despite changing the values of some variables, the Vue.js code continues to reference the previous values. I have attempted mult ...

Prevent clicks from passing through the transparent header-div onto bootstrap buttons

I have a webpage built with AngularJS and Bootstrap. It's currently in beta and available online in (German and): teacher.scool.cool simply click on "test anmelden" navigate to the next page using the menu This webpage features a fixed transparent ...

Trouble Arising from Making a POST Request to Spotify's API

I am currently developing a web application that allows users to search the Spotify Library, add songs to playlists, and then save those playlists to their Spotify Accounts. Almost everything is functioning correctly except for the saving of playlists thro ...