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

Shrink video size directly in the browser using JavaScript and HTML5 before storing or sharing it

Is there an optimal method for resizing and potentially trimming a video using Javascript, HTML5 or Webassembly in modern browsers before saving it to the Filesystem? What is the most effective way to edit a video within the browser? Here are some differe ...

The HTML form submission button fails to submit the form and instead just refreshes the page

I'm struggling to get the save button working on my Chrome Extension settings page. The .click() event doesn't seem to be activating at all. I've included my code below. Should I use the commented out button instead (see below)? HTML <! ...

modifying a mongodb array without actually updating it

Currently, I am facing an issue with updating the collection of users whose purchase dates have expired. When I attempt to save the changes, the user's role gets updated successfully but the purchase history does not reflect the changes. Below is the ...

How can you utilize positioning and margins with Flexboxes?

<template> <div class="flex justify-center"> <div class="h-px-500 md:w-1/6 bg-orange-200 text-center">1</div> <div class="h-px-500 md:w-1/6 bg-orange-300 text-center">2</div> <div class="h-px-500 md:w-1/ ...

Managing an iframes website using buttons and links: Tips and tricks

I am trying to create a website that includes an iframe for navigating through external websites using previous and next buttons. I also want to display the links on a sidebar so that users can click on them to automatically load the site in the iframe. I ...

Create an overlay effect when hovering in a Vue.js application

I am currently facing a challenge in implementing text display on image hover in vue.js. I have tried to replicate this functionality using an array with multiple images following this example: here. Although my vue file is quite extensive, the crucial pa ...

How can you efficiently access the 'app' object within a distinct route file?

When using Express 4, the default behavior is to load routes from a separate file like so: app.use('/', routes); This would load routes/index.js. I am working with a third-party library that directly interacts with the app object itself. What& ...

app.js at line 81010 triggers a Vue warning because of an error in the mounted hook. The error message states: "ReferenceError: $store is not defined

As part of my code refactoring process to incorporate vuex, I encountered 2 errors: app.js:81010 [Vue warn]: Error in mounted hook - "ReferenceError: $store is not defined" and ReferenceError: $store is not defined. Despite thinking that I imported vuex co ...

Retrieval of entity through REST Endpoint using ODataSetName for Custom Entity

In my restendpoint.js file, I have a function called retrieveRecord which is defined on this website I am working on a function that should trigger whenever the Programme (a lookup field) on the Application entity changes. The goal is to fetch the attribu ...

The JavaScript Discord Bot is having trouble connecting to a voice channel

I'm currently working on developing a discord bot using node.js. While I've successfully set it up to respond, I'm facing an issue with summoning it to a voice channel. Here is the snippet of code I am working with: switch (args[0]) { c ...

Looking for assistance on how to use Express JS to make a post request to insert data with an array of objects into a database. Can anyone provide guidance?

While utilizing ExpressJS for serverside functionality, I encountered an issue when making a post call with multiple objects in an array. The error message displayed is as follows: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to t ...

What is the best method for saving console.log output to a file?

I have a tree structure containing objects: let tree = {id: 1, children: [{id: 2, children: [{id: 3}]}]} My goal is to save all the id values from this tree in a text file, indenting elements with children: 1 2 3 Currently, I am using the following ...

Synchronization issue between VueJS, Firebase Auth, and Route Guards leading to race conditions

Running into an issue while integrating Firebase Auth with my Vue app. After a page refresh, a logged in user is not recognized as such and gets redirected to the login page when trying to access a protected route. This occurs because the initial callback ...

Ways to observe redux action flow within a component

I am currently developing a React application structured with the following elements: redux typesafe-actions redux-observable My query is: How can I trigger a UI action when a specific redux action occurs? For instance, if we have these asynchronous ac ...

Why does my script seem to be missing from this GET request?

Encountering an issue while setting up a page using npm and grunt. Request URL:http://localhost:9997/bower_components/requirejs/require.js Request Method:GET Status Code:404 Not Found The problematic html code is as follows: <script> ...

AngularJS - development of a service entity

After deliberating between posting in the Angular mailing list or seeking assistance from the JavaScript community, I have decided that this is more of a JavaScript question. Hopefully, the knowledgeable individuals on Stack Overflow can provide a quicker ...

Slideshow: I hope the Radio Button triggers the appearance of the next item in the rotation

I need to implement a carousel that displays the next item (Id="item2") when a specific radio button (Id="item1") is selected by default and another radio button (Id="item2") is pressed. Ideally, I would like to achieve this ...

Display Image After Uploading with AJAX

After spending nearly 3 hours working on implementing file uploads via AJAX, I have finally managed to get it up and running smoothly. Take a look at the code below: View <div class="form-horizontal"> <div class="form-group"> @Htm ...

"What could be the reason for web3.eth.getAccounts() method returning an empty array when used with console.log

Upon executing web3.eth.getAccounts().then(console.log);, I encountered an empty array and also received a warning stating ./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression. The project began w ...

Developing Webpart Postback logic in C# script

I am currently facing challenges with SharePoint webparts programming. I am unsure about how to trigger a postback for an object at a specific time. I have come across suggestions to use "javascript" for this purpose, but I am having trouble understanding ...