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

Firefox 3 fails to utilize cache when an ajax request is made while the page is loading

Upon loading the page DOM, I utilize jQuery to fetch JSON data via ajax like so: $(document).ready(function(){ getData(); }); ...where the function getData() executes a basic jQuery ajax call similar to this: function getData(){ $.ajax({cache: t ...

Drop draggable items on top of each other

I'm wondering if there's a way to drag jQuery elements into each other. To illustrate my question, I've duplicated this code (link) and made some style changes. Here is the updated version: Fiddle Link. In the current setup, you can drag e ...

Troubleshooting Challenges with JavaScript DOM Manipulation

I am facing an issue with a table where I need the first column to remain fixed when scrolling horizontally. The code snippet below works perfectly for the first column of td's, but fails to work for the tr's. Despite checking the code thoroughly ...

Tips for effectively passing navigation as props in React Navigation with Expo

How can I correctly pass navigation as props to another component according to the documentation? The navigation prop is automatically provided to each screen component in your app. Additionally, To type check our screens, we need to annotate the naviga ...

Why is my Bootstrap Carousel Switching Images but Refusing to Slide?

I've encountered a problem with my bootstrap carousel. The slide effect doesn't seem to be working, even though I have added the "slide" CSS tag. Instead of sliding, the images just quickly change without any transition. Here are some key points ...

The malfunctioning buttons are a result of embedding PHP code within a JavaScript if-query

I am experiencing an issue where my buttons are not functioning properly, preventing me from clicking on them. All variables have been correctly assigned values. Can someone assist me in resolving this? Thank you. ?> <script> ...

When utilizing the File System Access API, the createWritable() method functions perfectly within the console environment but encounters issues when executed

I've been diving into the File System Access API for an upcoming project and I'm struggling with using the createWritable() method. Specifically, I'm encountering issues with this line of code: const writable = await fileHandle.createWritab ...

When I upload a file using v-file-input, it displays two names

While working with nuxt, I made an interesting discovery. See the pattern here The top name is the file that was uploaded, and the bottom one is the target file name. I plan to remove the bottom name and replace it with the top. This is what I envision: E ...

Steps to retrieve an ext.js grid using data from a database

I've been struggling to make a basic Ext.js application work, which is supposed to pull data from a database and show it in an Ext.js grid. However, all I keep getting is "Failure:true". If you could help me identify the mistake, that would be great. ...

When the section comes into view on the screen, the CSS animation will play only one time

While browsing through , I found some fantastic animations that inspired me. The animations at the header seem to be standard CSS animations with delays. However, as you scroll down and other sections become visible, the animations reappear only once. Can ...

Guidance on implementing fallback font formats using FontFace API

I am exploring the FontFace API (not @fontface) and wondering if there is an easy way to include multiple font formats, similar to providing multiple sources in @fontface. Alternatively, is there a simple method to identify which font formats are supporte ...

What exactly happens behind the scenes when JSON.stringify() is called?

How does the replacer argument function extract keys and values from an object's value and map them to its key and value arguments in the JSON.stringify(value, replacer, space) method? I have grasped that the key of the object becomes the key paramet ...

Connecting JavaScript and PHP strings

My goal is to transfer a JavaScript string to a PHP processing script and compare them. Upon successful match, I intend to conduct a simple validation process and if it passes, send an email notification. To provide context, below is a snippet of my curre ...

The most basic method for monitoring changes in an object

An application needs to immediately update all clients with a large object when it changes. What is the most basic method to monitor changes in a Node.js object? Consider the following object: var obj = { num: 3, deep: { num: 5 } } A functi ...

What is the process for renaming folders with files in node.js?

The current method is effective for renaming a single folder with no files, but it fails when trying to rename a folder containing one or more files. const handleRenameFile = () => { const oldPath = `./${directory}/${fileName}`; const newPath = ...

Passing Parameters to Razor Pages Controller

Within my controller, there exists a function as follows: public ActionResult AddSubSub(int? idOfSubsub) { return RedirectToAction("Index", new { searchword = "" }); } I am able to invoke this function without providing any parameter. I attempted the ...

How to incorporate JSON into a d3.js calendar display?

Learning d3 charts and javascript has been quite challenging for me. After researching a lot, I successfully populated the chart with CSV data. Now, my next goal is to populate the chart with json data. This is the code I'm using, which is inspired ...

Managing Flicker Effect by Implementing Theme Switching and Using Local Storage in Next.js with Ant Design

I've been working on a new feature to switch themes (light/dark) dynamically in a Next.js application using Ant Design. Successfully integrating the theme switch with a toggle switch and useState hook, I'm faced with the challenge of storing the ...

An effective way to verify if a record has been successfully updated is by utilizing Sequelize's

Within this snippet of code, I made an update to a specific record in the IPAdress model. What is the best way for me to verify if the record has been successfully updated or not? let IPAdress = await model.IPAdress.update(data,{ where: { id } }); ...

Using Javascript regex to capture the image name from a CSS file

As I work with JavaScript regex, my goal is to extract the image name and extension as a capture group of CSS properties. Criteria Must start with "url" Followed by brackets Optional quotes inside brackets The location can include path information Must ...