To retrieve a property in Vue, you can use either the "this" keyword

Exploring Vue for the first time and navigating through accessing viewmodel data has me puzzled. When should I utilize this.property versus vm.$data.property.

In this scenario with a table where I can select rows, there are methods in place to select all rows and deselect all rows. When deselecting, I can access selectedRows using this.selectedRows. However, when selecting, I need to use rowTableVm.$data.selectedRow as this.selectedRows is not defined.

How do I determine when to use this. as opposed to vm.$data.

<tbody>
  <tr v-for="row in get_rows()">
    <td>
      <input type="checkbox" v-bind:value="row.id" v-model="selectedRows">
    </td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</tbody>

var rowTableVm = new Vue({
        el: '#rowTable',
        data: {
            rowList: [{..},{..}],
            selectedRows: []
        },
        methods: {
            get_rows: function get_rows() {
                return this.rowList;
            },
            deselect_rows: function () {
                this.selectedRows= [];
            },
            select_rowse: function () {
                this.deselect_rows();
                this.get_rows().forEach(function (entry) {
                    rowTableVm.$data.selectedRows.push(entry.id);
                });
            }
        }
    });

Answer №1

The issue you're encountering is related to scoping. When using this inside a forEach loop, it may no longer be bound to the Vue instance. To solve this problem, you can store a reference in a variable before entering the loop like so:

select_rowse: function () {
    this.deselect_rows();
    var this_vue_instance = this;
    this.get_rows().forEach(function (entry) {
        this_vue_instance.selectedRows.push(entry.id);
    });
}

Avoid relying on vm.$data whenever possible. Having multiple references to a variable scattered throughout your code or needing to rename it can lead to issues. Using this ensures consistency. Use a variable reference only when absolutely necessary, which should be rare.

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

Vue: Error - Unable to execute _vm.myFunction as it is not a function

I'm currently working on adding a basic button to a .vue file that will log a message to the console. Here's the code I have so far: <template> <div> <button v-on:click="sayHello()">Click me</button> < ...

Navigating with firebase authentication and angular routing

Currently, I am in the process of developing an ionic app using version 4. For this project, I have decided to utilize firestore as my database and implement firebase-authentication for user login and registration functionalities. However, I have encounter ...

Upon redirection, my JavaScript codes cease to function properly and require a page refresh to resolve

Upon redirecting to another page with included JS codes, my main.html does not function properly until I refresh the page. What steps can be taken to resolve this issue? 0.html <body data-theme="b"> <div class="p2" data-role="page" id="p2"> ...

Iterating through an array with conditional statements

I am currently considering the best approach to loop through an array in my code before proceeding further. I have some concerns about the link (var link = ... ) and the if statement. Is this the most optimal way to iterate over array1 and compare the val ...

PHP displays the array returned by Ajax as "[object Object],[object Object]"

When working with Jquery, I am creating two arrays - one embedded inside the other. Here is an example of what it looks like: arrayOne = [{name:'a',value:1}, {name:'b',value:2}] var arrayTwo = [{name:'foo',value:'blah&ap ...

React: Oops! Looks like there's an issue - this.props.update is not defined as

Hello everyone, I'm diving into the world of programming for the first time and I might ask some silly questions along the way. Currently, I'm working on integrating a date picker into a search application built with React. The user should be ab ...

Stop mega menu items from disappearing when hovered over

I'm currently working on a web page that features a mega menu. When I hover over the mega menu, it displays its items. However, when I try to hover over the items, they disappear. Here is the HTML code snippet: <li class="dropdown mega-dropdown m ...

Troubleshooting problem with Electron and sqlite3 post application packaging

I've been facing various challenges with Node and databases lately, hence the numerous questions I've posted here recently. Here's some background: I have an Electron app with an AngularJS frontend. On the electron side, I run an express s ...

The background image shifts dynamically with a parallax effect as the page is scrolled

I need help solving a parallax issue that I'm currently facing. On my webpage, I have a background image positioned at the top with a parallax effect achieved through background-position: fixed. However, I now require the image to scroll along with t ...

Ways to address the problem of returning assignments

I encountered an issue while working on my code Error message: Arrow function should not return assignment no-return-assign The problematic code snippet is as follows: await DB.Place.find( match, // key to filter (err, doc) => (listOfObje ...

Update an existing JSON document

Looking for a solution to update the json file while retaining specific strings and values? const fs = require('fs'); var logPath = 'log.json' var logRead = fs.readFileSync(logPath) var logFile = JSON.parse(logRead) LogChannel = &apo ...

Tips for Uploading Large Images to Backend API in Next.js

As I work on building my portfolio using NextJS, I encountered an issue with the Project Functionality. When converting images to base64 and sending them to an API for uploading on Cloudinary, everything runs smoothly as long as the total size of the req ...

Utilize AxiosAbstraction to transmit a Patch request from a Vue.js application to a PHP backend

I need help with sending a PATCH request to update the birthdate of a user (promotor) from Vue.js frontend to PHP backend. The issue I'm facing is that the new date of birth is not getting saved in the database, and the existing date of birth in the d ...

Struggling with making changes to a instantiated "this" object within a pseudo javascript class

If you scroll down to the bottom of this post, you'll find a workaround or possible solution. I've been grappling with understanding how pseudo classes work together to achieve the task I'm attempting (explained in the code below). It might ...

How to utilize FileReader for parsing a JSON document?

I'm currently facing an issue while attempting to read and copy a JSON file uploaded by the user into an array. When using .readAsText(), the returned data includes string formatting elements like \" and \n. Is there a way to utilize FileRe ...

What is preventing the JQuery dialog from opening?

When I try to trigger a dialog box by pressing the enter key, it is not working as expected. Instead of opening the dialog, it just hides the text. Can someone help me understand what might be causing this issue? <!doctype html> <html lang="en" ...

Utilize jQuery to transform array values into date objects

I am receiving an array from a .net controller. The values I am getting for dates are: /Date(1445256000000)/ and /Date(1445256900000)/ Instead of this, I need to convert these into proper date values. Now that I have an array of objects, I want to upda ...

What is the process for implementing Autocomplete in JsHelper?

Is it possible to create an Ajax Autocomplete using only pure JsHelper in JavaScript? Thank you, Celso ...

Is it necessary for JavaScript functions to be stored in a separate file in order to be invoked?

Here is the scenario that unfolded: Within a .php file, I had the following form: <form action="/flash_card/scripts/create_user_gate.php" onsubmit="return validateForm()" method="post"> <table align="center"> ...

Tips for assigning an ID to a span element within a for loop

I am facing a challenge where I need to assign IDs to span tags that do not have the id attribute. These IDs need to be assigned sequentially by incrementing through a for loop and passing my geneologicalSequenceNumber into each span tag. Can you guide me ...