When calling a Vue.js method, it appears to be undefined

Currently, I'm working on developing a Chrome extension using Vue and Browserify. Within my component file, I'm attempting to invoke a method called animateBackground from the mounted hook. However, when checking the console, an error message is being displayed. How can I properly access the data and methods within the component?


    export default {
      name: "app",
      data() {
        return {
          'message': "thgdfseaw"
        }
      },
      mounted() {
        chrome.storage.local.get("bingImage", function(output) {
          if (output != undefined || output != null) {
            console.log(this.message);
            this.animateBackground(output.bingImage.base64);
          }
        });
      },
      methods: {
        animateBackground(base64) {
          $("#app").animate({ opacity: 0 }, "slow", function() {
            $(this)
              .css({ "background-image": "url(" + base64 + ")" })
              .animate({ opacity: 1 });
          });
        }
      },
      components: {
        AppSection
      }
    };
  

https://i.sstatic.net/Arwtb.png

Answer №1

The callback function does not refer to your vue instance. You can use the console.log method to determine its value. There are several ways to work around this issue. One solution is to utilize ES6 arrow function syntax, or you can create a new variable outside of the callback and assign this to it. Here is an example:

export default {
      name: "app",
      data() {
        return {
          'message': "thgdfseaw"
        }
      },
      mounted() {
        var _vue = this // << here
        chrome.storage.local.get("bingImage", function(output) {
          if (output != undefined || output != null) {
            console.log(_vue.message); // << then access it like this
            _vue.animateBackground(output.bingImage.base64);
          }});
  },
  methods: {
    animateBackground(base64) {
      $("#app").animate({ opacity: 0 }, "slow", function() {
        $(this)
          .css({ "background-image": "url(" + base64 + ")" })
          .animate({ opacity: 1 });
      });
    }
  },
  components: {
    AppSection
  }
};

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

What is the best way to store React form data in a queue for future processing?

I am currently developing a ticketing system in React, utilizing Node.js for the backend and Python for the email server. My goal is to process form submissions by extracting all the form data, creating an instance of a plain JavaScript class with only a ...

"Addclass() function successfully executing in the console, yet encountering issues within the script execution

I dynamically created a div and attempted to add the class 'expanded' using jQuery, but it's not working. Interestingly, when I try the same code in the console, it works perfectly. The code looks like this: appending element name var men ...

Using Selenium and Python to download audio files that require JavaScript to load

Currently, I am in the process of developing a script to streamline the task of downloading text and audio files from a specific website using Python and Selenium. The targeted website is: (yyyymmdd) import requests from time import sleep from selenium ...

What is the significance of the '|' operator in Vue.js source code "vnode.js"?

Can someone please explain the meaning of the | operator? I found a code snippet in src/core/vdom/vnode.js export default class VNode { tag: string | void; data: VNodeData | void; children: ?Array<VNode>; text: string | void; elm: Node | ...

Angular 6: Issue with displaying data on the user interface

Hello! I am attempting to fetch and display a single data entry by ID from an API. Here is the current setup: API GET Method: app.get('/movies/:id', (req, res) => { const id = req.params.id; request('https://api.themoviedb.org/ ...

What is the procedure for assigning an element's background-color to match its class name?

Is there a way to use jQuery to make the background color of a span element match its class? $(function() { $("span").css("background-color") }); span { display: inline-block; width: 5px; height: 5px; border: solid #0a0a0a 1px; } <script src= ...

AngularJS directive doesn't refresh template when scope values are fetched dynamically through ajax requests

Attempting to give this question a precise title as possible, I find myself struggling with an issue in AngularJS. While trying to showcase my problem through a jsfiddle, it turned out to be too reliant on multiple files and not yet accessible online. So p ...

Having trouble importing d3.js and typescript in IntelliJ?

Encountering errors in browsers' console when utilizing d3.select() in typescript code. Despite trying alternative methods like d3-timer.now(), the issue persists. As a newcomer to typescript, I am utilizing intelliJ Ultimate 2019.1. Through npm, I h ...

Having trouble accessing properties of an undefined object when trying to read 'credentials' in Firebase Auth within ReactJS

I need to verify the user's password again before allowing them to change it. Currently, my Firebase Auth setup is defined in Firebase.js and exported correctly //appConfig = ...(all the configurations here) const app = firebase.initializeApp(appConf ...

The issue of calling the store() function on null in Laravel with Nuxt

I'm encountering an issue with saving data in Laravel from my Nuxt Application. I successfully created data using Postman, but for some reason it's not working here. Controller $book = Book::create([ 'name' => $request ...

Exploring Dynamic Component in Vue.js for Efficient Data Access

My website has a basic layout displaying search results in either table or list style. The Vue components I am using are results-array and results-list. Everything works perfectly until I switch from the first component to the second one. At that point, ...

Angular 8 does not allow for the assignment of type '{}' to a parameter

I have a unique approach for managing errors: private handleErrors<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); this.record(`${operation} failed: ${error.m ...

Unraveling unicode escape sequences in JavaScript strings

My code includes a string like \uC88B\uC544\uC694. When I use this string in a node repl (v7.4.0), it displays '좋아요' correctly. However, when I try to use the same string in the following code snippet, it does not work as ex ...

Associating mongoose object with a DTO object in an Express.js application

I am looking for a way to transform mongoose result objects into DTOs for my views. Here is an example query that returns a mongoose object: const returnedData = (err, result) => { //Result object is a schema from Moongose cb(err, re ...

Issues with Angularjs $http.get functionality

On the server side of my ASP.net MVC application, I have a method that looks like this: [HttpGet] public JsonResult GetTrenings(string treningId) { var tempId = Guid.Parse(treningId); var trening = TreningService.GetTreningById ...

Adding query parameters to the end of every link on a webpage

Wondering how to automatically add GET values to the end of each anchor href on a webpage? For instance, if you input google.com?label=12&id=12 I want to ensure that "?label=12&id=12" gets added to the end of every single href in an anchor tag on ...

Exporting JSON data to CSV or XLS does not result in a saved file when using Internet Explorer

Presented below is the service I offer: angular.module('LBTable').service('exportTable', function () { function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel, fileName) { //If JSONData isn't an object, parse the ...

Encountered an issue while verifying req.params.id in an express.js route

Hi there, I'm reaching out for assistance with my first question on StackOverflow. As a newcomer to full-stack programming, I've encountered an issue while attempting to GET data from a JSON file via a GET Method on my local Node.js Express serve ...

Ways to showcase HTML table in a four-column layout/grid

Delving into Dynamic HTML table creation, I'm currently using jquery for rendering purposes. At the moment, I am only displaying the table. The Goal I aim to segment my table into four columns or a grid structure Something akin to this: https://i. ...

Utilizing React Native to dynamically generate buttons through a loop

I am currently working on retrieving data from the Eventbrite API. The information I am hoping to extract is the event names, which will then be added to a list. Within the render function, I aim to dynamically create buttons based on the number of event ...