Vue.js error: Trying to access an undefined property

Here is my Vue instance setup:

const vueApp = new Vue({
    el: '#vue-wrapper',
    data: {
        items: []
}});

Utilizing a v-for loop in index.html.eex:

<div v-for="item in items[0].subItems">{{ item.name }}</div>

In this script, I populate the 'items' array with server-side data on document ready, passed from my Phoenix server during rendering:

<script type="text/javascript">
      jQuery(document).ready(function() {
          //Assigning server-side data
          vueApp.items = <%= raw(@items) %>;
          console.log(vueApp.items);
      });
</script>

The log function confirms the correct list of items. However, I encounter an error when trying to access them in the v-for loop:

vue.min.js:6 TypeError: Cannot read property 'subItems' of undefined

I seem unable to access the first element as if the 'items' array is not yet populated. How can I resolve this issue? The initialization in the index.html.eex file is necessary for retrieving data from the server using EEx syntax.

Answer №1

let vueInstance = new Vue({
  el: '#app',
  data: {
    items: [{ subitems: [] }],
})

You forgot to define the "subitems" property in your example. Here's the corrected code.

Answer №2

Consider enclosing your v-for directive within a v-if statement with the condition "flag"
Initialize the flag variable in the instance as false
Update the flag to true once the data is retrieved from the backend...

Answer №3

Here is a suggestion:

<div v-if="items.length > 0" v-for="item in items[0].subItems">{{item.name}}</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

Steps for linking a keypress to trigger a specific action

I need help creating a script that will redirect to a URL when a button is clicked. Below is the code I have developed. HTML : <a id="#next" href="example.com">↵</a> <a id="#previous" href="example.com">↳</a> JS : $(document ...

Utilizing jQuery AJAX to efficiently handle branching based on the result received

I've successfully set up my first AJAX call with jQuery. The only thing left to do is to check the result from the PHP page for any database errors and display an error message if necessary. Here's the current Javascript code: <script type=" ...

Enhancing error handling with Axios in Vue.js

I'm facing an issue with global error handling in axios while making calls in Vue.js. Despite trying various methods, such as triggering user logout, the code block after the axios call still gets executed when an error occurs. Is there a way to preve ...

How to Fix Items Being Pushed Down by 'Particleground' Jquery Plugin Due to Z-Index and Positioning

I'm grappling with understanding z-index and positioning, despite reading various questions and articles on the topic. Currently, I'm attempting to incorporate a Jquery Plugin called 'Particleground': https://github.com/jnicol/particle ...

Pause the counter based on the data attribute containing multiple values

I have a collection of div elements, each with a unique data-attribute value. My goal is to display these values in the divs using JavaScript by incrementing a counter. const numbers = document.querySelectorAll(".number"); console.log(numbers); let c ...

Tips for generating a single sitemap in Next.js

Utilizing the next-sitemap package to generate a sitemap, I have both dynamic and static pages. This is what my next-sitemap.config.js file looks like: module.exports = { siteUrl: 'https://example.com', generateRobotsTxt: false, excl ...

Methods for organizing consecutive elements within an array in Javascript/Typescript

Let's explore this collection of objects: [ { key1: "AAA", key2: "BBB" }, { key1: "BBB", key2: "CCC" }, { key1: "CCC", key2: "DD ...

transition from mapStateToProps to using hooks

Just dipping my toes into the world of React (hooks) and learning by writing code. I'm grappling with converting MapStateToProps to hooks, specifically stuck on one part just before 'currentItem'. Here's the original code snippet: co ...

Steps for generating a time selection dropdown menu

My issue is with the functionality of my timepicker dropdown. Below is the code I am currently using: $(document).ready(function() { $('.timepicker-input').timepicker({ timeFormat: 'h:mm p', interval: 60, minTime: ' ...

Would you like to learn how to extract data from a specific textbox using jQuery and save it to a variable when the textbox is in

Below is a textbox that I am working on: <input type="text" name="company" id="company" required /> I am trying to figure out how to use jQuery to capture the values inside the textbox whenever they are typed or selected. Despite my efforts, I hav ...

What is the method for customizing the background color in a .vue file using Bootstrap?

Can anyone assist me in updating the background color of a div class from grey to white? The code is within a .vue file using Bootstrap and includes an enclosed SVG file. Here's the snippet: <div class="text-left my-3 bg-white"> <button var ...

Incorporating Ruby on Rails: Sending a fresh POST request to API and instantly

I'm a beginner in the field of ruby on rails. Our website allows users to search and receive a list of results. Now, I want to incorporate sorting functionality for the results (by price, rating, etc). The API handles the sorting process, so all I ne ...

Continuously animate a series of CSS properties

Here's the code snippet I'm working with: @keyframes ball1 { 0% { transform: translateX(0px); opacity: 0%; } 50% { opacity: 100%; } 100% { transform: translateX(120px); opacity: 0%; } } @keyframes ball2 { 0 ...

What are the steps for importing KnockOut 4 in TypeScript?

It appears straightforward since the same code functions well in a simple JS file and provides autocompletion for the ko variable's members. Here is the TypeScript code snippet: // both of the following import lines result in: `ko` undefined // impo ...

What steps do I take to eliminate this additional content?

Currently working on a web messenger project and facing an issue with a specific bar that I want to remove from my interface: Within the Home.blade.php file, the code snippet looks like this: @extends('layouts.texter') @section('content&ap ...

Is it advisable to utilize media queries and transform: translateY(-%) to position content above the mobile keyboard?

I've been struggling for nearly a whole day and could really use some assistance. I'm having trouble understanding how chat web apps manage to work around this particular issue. There have been numerous forum posts discussing the problem: I am tr ...

When the browser is not in the foreground, clicking on the Bootstrap datepicker with Selenium does not register

When you click on the input field <input id="dp1" class="span2" type="text" value="02-16-2012"> If the browser is in the background, the datepicker popup will not display. Even using javascript or jquery to click the input field does not show the ...

Encountering the React Native error message "TypeError: Object(...) is not a function" while using react navigation stack

I am currently facing an issue with my react-navigation-stack. My suspicion lies in the dependencies, but I am uncertain whether that is the root cause. The objective at hand is to create a text redirecting to another page. If there is any irrelevant code, ...

Is there a way to make my code on Google Sheets work across multiple tabs?

My Google Sheets code successfully pulls information from the main tab into my CRM Software every time someone fills out a form online. However, I'm struggling to get the script to run for multiple tabs on the same spreadsheet. I've tried a few s ...

What is the best way to share information among Vue3 single file component instances?

I am seeking a way to have certain data in my single file component shared among all instances on the page, similar to how static variables work in PHP/C. To achieve this, I understand that in single file components, we declare data as a function like so: ...