Is there a way to access a computed property within methods?

Currently, I am utilizing this particular package to implement infinite scrolling in Vue.

In order to continuously add new elements during each scroll, I fetch JSON data from my API server and store it in a data object. Subsequently, I divide the array into groups of four before saving them back to variables. However, the challenge arises when trying to append elements using an event handler method that is unable to access any variable from the computed property. As a newcomer to Vue, I have struggled to find relevant information on this issue. Below is the code snippet:

 export default {
  name: 'main',

  data: () => ({
    items: [],
    line: []
  }),

  async created () {
    this.items = await fetch('/videos').then(res => res.json())
  },

  computed: {
      columns: function() {
          return chunk(this.items, 4)
      }
  },

  methods: {
    onInfinite() {
      setTimeout(() => {
        const temp = []
        const len = this.columns.length
        for (let i = len + 1; i <= len + 5; i++) {
          temp.push(this.columns[i])
          console.log(this.columns[i]) //It prints 'undefined'
        }

        this.list = this.list.concat(temp)
        this.$refs.myRefName.$emit('$InfiniteLoading:loaded')

      }, 700)
    },
  },
  components: {
    InfiniteLoading
  }
 }

Answer №1

let arrayLength = this.columns.length // determine the length of the 'columns' array

Next step:

for (let index = arrayLength + 1; index <= arrayLength + 5; index++) {
  ...this.columns[index]

You are attempting to access indexes beyond the array's length, which will return undefined values.

A better approach would be to loop through each element in the columns array like this:

for (let column of columns) {
   for (let item of column) { // assuming that each 'column' is an Array(4)
      console.log(item)

This code should work if your columns is an array containing 'chunk' arrays with 4 elements in each sub-array.

Answer №2

Employ this specific keyword in order to access the computed method as demonstrated below:

item.push(this.column[i]);

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

Utilize toggle functionality for page rotation with rxjs in Angular framework

Managing a project that involves a container holding multiple cards across different pages can be overwhelming. To address this, the screen automatically rotates to the next page after a set time interval or when the user presses the space bar. To enhance ...

Converting an HTML form with empty values into JSON using JavaScript and formatting it

While searching for an answer to my question, I noticed that similar questions have been asked before but none provided the solution I need. My situation involves a basic form with a submit button. <form id="myForm" class="vertically-centered"> ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

Creating a JSON object using various inputs through AngularJS

Just starting out with Ionic, Angular, and Firebase. This might be a silly question :) I'm working on an app using Ionic + Firebase, and I want to create a JSON object from multiple inputs. The interface looks like the image below: https://i.stack.i ...

Ways to retrieve the text of the chosen radio button label with the help of jQuery

There is a radio button on my webpage that looks like this: <div id="someId"> <label class="radio-inline"> <input name="x" type="radio" onchange="GetSelectedVal();">Yes</label> <label class="radio-inline"> ...

Is there a way to transform a stringified array into an array in JavaScript if I do not have access to the original string?

Recently, I encountered a challenge where I had an array of items enclosed within "", and not '' (if that distinction matters): "['item 1', 'item2', 'item 3']" I am interested in converting it to ...

The issue arises when the view fails to load while simulating a backend

Trying to test a specific element of the user interface requires a particular request to the backend with predefined data while allowing all other requests to pass through. Here's a more readable version in coffee script: describe 'select2 combo ...

Pinterest-style Angular-UI-Router modal

I am currently working on an app that features a gallery showcasing similar functionalities to . In Pinterest, clicking on a pin displays the pin page above the existing gallery without any information about the background gallery shown in the URL. Users c ...

Create a JavaScript script within a CSS file

I'm attempting to create this using only CSS: Codepen and I would like to achieve the same effect but solely with CSS. This is what my CSS looks like: .text{ --a: calc(var(--a);*0.82+(1.5-var(--b);)/10); --b: calc(var(--b);+var(--a);); transfor ...

Having difficulty converting the string data to HTML using JavaScript in a Node.js Express application

In my app.js file, I will be sending data to an EJS file. app.get('/', function (req, res){ Blog.find({}, function(err, fountItems){ Blog.insertMany(defaultBlog, function(err){ }) } res.render( ...

What is the best way to keep the navbar contained within the parent div (hero image) no matter the size of the screen?

After working on adjusting my website layout for different screen sizes, I encountered an issue with the navbar overflowing the parent image when viewed on my laptop. Despite trying both relative and absolute positioning for the .navbar element and setting ...

React component rendering twice due to width awareness

In a React component that I've developed, I have utilized ResizeObserver to track its own width. Within this component, two divs are rendered with each having a "flex: 1" property to ensure equal width distribution. Under certain conditions, such as w ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...

PHP and JavaScript are two powerful programming languages that are

While I understand that PHP and JavaScript operate in different locations, I am curious to know if there is a way to incorporate some PHP code into my JavaScript file. I need to create unique URLs for linking to profiles and news posts, such as /#/news/IDH ...

What are the best strategies for handling complex task operations in Node.js Express.js?

How can I effectively manage lengthy task functions in Node.js Express.js to prevent timeout errors? Currently, my application includes a time-consuming function that does not require an immediate response but still needs to execute its tasks. How can I en ...

What is the best way to remove a property from an object in React if the key's value is set to false?

I'm currently working on a form component and I've encountered an issue. Whenever I submit the form, it returns an object with various fields such as email, fieldName1, fieldName2, first_name, last_name, and organization. Some of these fields are ...

Literal Route Waypoints Guidance Service

I am currently working on an angularjs directive that utilizes the Google Maps Direction Service. In my controller, I have a getFunction that watches for changes in a scope variable. Once the scope variable changes, it triggers the calculateAndDisplayRoute ...

Is there a way to capture the click event of a dynamically generated row within a panel?

Could you please advise on how to capture the click event of a row that is generated within a panel? I have successfully captured events for rows generated on a page using the , but now I need assistance with capturing events from rows within a panel. I c ...

Angular error ReferenceError: $Value is not defined in this context

As a newcomer to AngularJS, I am facing an issue while passing a list from the HTML file to the backend for processing. The error message ReferenceError: $Value is not defined keeps popping up. Within my controller file, I have a function named test. The ...

The Add and Update functions of an AngularJS application are malfunctioning in Internet Explorer

Encountered a situation where updates and additions in IE show results in Chrome :D // Extract category object and id from the parent $scope.addNewCategory = function (category, parentId) { $scope.resetError(); category.parentId = par ...