changing vue.js data value within a nested method

When working with Vue, I am aware that I can update the value of a data property within a method using this.variable_name. However, I encountered an issue while attempting to do this from within a method with a nested sub-method (due to making an ajax request) where I received an error stating that it was undefined.

The code snippet I have is:

var myvue = new Vue({
    name: "MyVue",
    el: '#my-vue-id',
    data: {
        fields: field_list // this is set in another js method elsewhere
    },
    methods: {
        reject: function (index, objectid) {
            if (confirm("Are you sure?")) {
                $.get("/reject/" + objectid, function (data) {
                    if (data.success == true) {
                        $("#" + objectid).fadeOut(400, function() {
                            this.field_list.splice(index, 1);
                        });
                    } else {
                        alert('Failed to delete.');
                    }
                });
            }

        }
    }
});

I attempted setting var self = this; within the $.get method and then trying to splice self.field_list, but in both cases, I received an error stating

Cannot read property splice of undefined
.

EDIT since I may have been unclear-- the field_list is being populated. If I were to do this.field_list.splice outside the ajax function, it works fine. The problem lies in accessing external scope from within the vue methods.

Answer №1

When a callback function is called, it does not have access to your Vue instance as its context (this). To solve this issue, you can use arrow functions for your callbacks or store this in a variable and refer to that instead.

Answer №2

Make sure to declare the var self = this; statement outside of the $.get function in order to avoid scope issues. This way, you can access the correct scope when using

self.field_list.splice(index, 1);
inside the $.get method.

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

Tips for Developing Drag Attribute Directive in Angular 2.0

Currently, I am referencing the Angular documentation to create an attribute directive for drag functionality. However, it seems that the ondrag event is not functioning as expected. Interestingly, the mouseenter and mouseleave events are working fine ac ...

NuxtJS (Vue) loop displaying inaccurate information

I have a dataset that includes multiple languages and their corresponding pages. export const myData = [ { id: 1, lang: "it", items: [ { id: 1, title: "IT Page1", }, { ...

In my sequence of Promises, a "reject is not defined" error led to the rejection of a Promise

In my code, I set up a chain of Promises like this: let promise = new Promise((resolve, reject) => { imgToDisplay.onload = () => { resolve(imgToDisplay.width); } }) .then((result) => { window.URL.revokeObjectURL(imgToD ...

Align the camera to be perpendicular with the ground

Ensuring that my fly camera always remains parallel to the ground is crucial to me. Specifically, I need my camera's right vector to always be (1,0,0). To achieve this, I have developed a customized Camera Controller in three.js that simulates unique ...

Bootstrap modal assistance does not function properly when used together with ajax requests

I'm experiencing an issue with a small class project where the data is not being inserted into the database. I collect the data using a bootstrap modal and pass it to the php file using ajax. The problem seems to be occurring when executing the script ...

Conceal any elements containing specific numbers in their IDs

Looking for assistance, I am attempting to simplify and provide a basic example: <div id="tree_div"> <ul> <li id="tree_li_401">401</li> <li id="tree_li_101">101</li> <li id="tree_li_301">301&l ...

Issues with Skrollr JS on mobile device causing scrolling problem

Currently facing an issue with Skrollr js. It is functioning perfectly in web browsers and mobile devices. However, there seems to be a problem when tapping on a menu or scrolling down arrow as it does not initiate scrolling. Assistance would be greatly ...

Maximizing the potential of $urlRouterProvider.otherwise in angular js

I am encountering an issue with redirecting to the login screen when there is no UABGlobalAdminId in my storage. I have tried using $urlRouterProvider.otherwise but it doesn't seem to be functioning properly. When I attempt to debug, the console does ...

Refreshable div element in a Code Igniter-powered web application

I am encountering difficulties with automatically refreshing my div using the CodeIgniter framework. My goal in the code snippet below is to have the particular div with id="lot_info" refresh every 1 second. The div is not refreshing, and an error message ...

What is the best way to search for all results in MongoDB that have x appearing in any property?

Is it possible to search for all pictures in the mongoose framework with node and express that contain a specific parameter, regardless of which property holds that parameter? For example: If I enter "John Snow" in the search bar, I want to see all pictur ...

Is it obligatory to reply with status code 200 in Express?

Is it required to explicitly include a status 200 code in the response or is it set automatically? response.json({ status: 'OK', }); vs. response .status(200) .json({ status: 'OK', }); Upon testing the route in my browser, ...

Utilizing jQuery to submit the form

After clicking the search icon, it displays an alert with the message ok, but not h. Based on the code snippet below, it is intended to display alerts for both ok and h. <?php if(isset($_POST['search'])){ echo "<script type='text/ ...

A new marker has been created on the Ajax Google Map, however, the old marker is still displaying as

Hey, I'm currently working on retrieving marker latitudes and longitudes using Ajax. I am receiving Ajax data every second and successfully creating markers within a specific radius. However, I'm running into an issue with updating marker positio ...

Encountering a dilemma during the docker build process with npm install is frustrating, especially when faced with an error message like: "Invalid response body when attempting

Encountering a docker build issue with npm install that seems to only occur inside the docker environment. The process works perfectly on my operating system Error Step 6/8 : RUN npm cache clear --force && npm install --legacy-peer-deps ---> ...

Eliminating duplicate loading of jQuery in Django SmartSelect

I'm facing an issue with Django's app, smart select, as it tries to load jQuery on its own. I've already loaded jQuery in the header and then loaded JQuery UI related stuff. However, smartselect also loads jQuery again in the body, causing p ...

Small jumps occur when implementing the scrollTop jquery animation

I've encountered an issue with the scrollTop jquery animation that I can't seem to resolve. It seems to micro-jump right before the animation, especially when there is heavier content. I'm puzzled as to why this is happening... Here's ...

Issue with Nextjs 13: Unable to locate 'src/app/dashboard/layout.tsx' (deleted optional layout)

Deciding to start a fresh Nextjs 13.4.5 project, I set up an app directory. Within the app directory, I created a new dashboard directory and added page and layout components. Everything seemed to be functioning smoothly with two layout components - one i ...

Developing desktop applications using C# scripting

I currently have a C# desktop program that is able to work with new C# plugins. My goal is to modify the existing C# application to allow for scripts to be used as plugins. These scripts could be in JavaScript, Windows Script Host (WSh), or any other form ...

Modifying numerous array keys/names in JavaScript

Alright, I have an array named arrayObj containing three objects: arrayObj[0], arrayObj[1], and arrayObj[2]. All of these objects have the key name["user"] repeated three times. To change these key names using a function, here's what I've come up ...

A dynamic context menu using jQuery within AJAX-loaded content

After spending hours searching for a solution without success, I am turning to this forum for help (I have come across similar questions but none of them have solved my issue). The problem I am facing is with implementing a custom context menu on a page t ...