Tips for retrieving the 'Created' value in vue.js

I am currently trying to fetch API JSON data for a weather widget, but unfortunately it is returning null. While I am able to retrieve the JSON data successfully, I am struggling to handle this value.

Below is my HTML code snippet:

<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script type="text/javascript" src="./js/jquery-3.3.1.min.js"></script> 
</head>
<body>
  <script>
    /* $(document).ready(function(){
      $.getJSON(url, function(json){
        console.log(json.location.name);
      })
    })/*/
  </script>
  <div id="app" >{{Country}}</div>
  <p v-if="isLoading">Loading</p>
  <script type="text/javascript" src="./js/app.js"></script>
</body>     
</html>

Here is my JavaScript code snippet:

window.addEventListener('load',()=>{
  var app = new Vue ({
    el: '#app',
    data:{
        Country : null,
        Temp : null,
        Icon : null,
        isLoading : true,
    },
    created(){
      var url ="http://api.apixu.com/v1/current.json?key=a69259fba9904700964121622190801&q=Nazilli";
        $.getJSON(url,function(json){
            console.log(json);
            this.isLoading = false;
            this.Country = json.location.name;
            console.log(this.Country);
        });
      },
   })
});

Answer №1

If you find yourself losing the context within the callback of $.getJSON, where it no longer points to the Vue instance inside the function call, there are a couple of solutions.

One option is to bind this directly to the function:

$.getJSON(url, (function (json) {
  //...
}).bind(this));

Alternatively, you can use a fat arrow function:

$.getJSON(url, (json) => {
  //...
});

Answer №2

The alteration of this within the getJSON function is crucial. Remember to store the original this reference.

var url = "http://api.apixu.com/v1/current.json?key=a69259fba9904700964121622190801&q=Nazilli";
var self = this; // store the current context in the self variable
        $.getJSON(url, function(json) {
            console.log(json);
            self.isLoading = false;
            self.Country = json.location.name; // utilize self instead of this
            console.log(self.Country);
        });

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

Generate a new passport session for a user who is currently logged in

I am currently utilizing passport js for handling the login registration process. After a new user logs in, a custom cookie is generated on the browser containing a unique key from the database. Here's how the program operates: When a new user logs ...

Switch Focus and Collapse Submenus upon Menu Click in Recursive React Menu

I've created a dynamic menu system in React using Material-UI that supports recursion for submenus. I'm aiming to implement the following features: 1. When a menu item is clicked, all other open submenus should close and focus on the clicked men ...

State change shows the previous and current values simultaneously

I've been working on updating the values of initUsers on the DOM. The initial state values work fine, but when I try to update initUsers, it displays different values than expected. Essentially, entriesNum receives a number as an event and changes th ...

I would like to give the option for file uploads, but the form refuses to submit unless a file is uploaded

I've recently developed a form in React and React Bootstrap, and I've encountered an issue with the file upload feature. I want the file upload to be optional, but when I try to submit the form without uploading a file, it doesn't work as ex ...

Oops! The page you're looking for at /api/tasks

Whenever I try to access: http://localhost:3000/api/tasks, I keep getting a "Cannot GET /api/tasks" error message. This is my server.js: var express = require('express'); var path = require('path'); var bodyParser = require('body ...

Decoding JSON to extract nested dictionaries in Python

My json file contains an object with a dictionary nested within it: { "__class__": "monster", "name": "Mugger", "level": 1, "hpTotal": 20, "attacks": ["Sword", "Knife"], "stats": { "AC": 12, "STR": 11, "DEX": 12, ...

Learn the method of conditionally resetting the state count using React hooks

When a user submits the form, the handleSubmit function runs to count the number of li elements with class names containing "show" within the search results div. It adds up these counts using setStoreCount(prevCount => prevCount + 1) and updates the UI ...

Fade in text effect using jQuery on a Mac computer

Trying to create a smooth text fading effect across different browsers using jQuery. In the example below, you may notice that during the last part of the animation when the text fades in, the font weight suddenly increases causing a jerky/clunky appearan ...

Is it possible to prevent the selected option from being available in other select lists using AngularJS?

Can anyone help me figure out how to disable an option in one select list when it is selected in another using AngularJS? I have set up a select list for From Year and To Year with ng-repeat, which is working fine. Now, I just need to implement the functio ...

Populate a Textbox Automatically using a Dropdown List

MVC 4 Changing multiple display fields based on DropDownListFor selection Having some issues trying to implement the solution mentioned above. It seems like there might be a problem with either my javascript code or the controller. JavaScript in View ...

Assign various instructions for each router view

https://jsfiddle.net/guanzo/8fdbcaxo/2/ In my Vue instance, there are 2 router-view's named foo and bar. I am looking for a way to conditionally assign directives based on whether the current router-view is displaying a foo or bar component. Currentl ...

Select box failing to display default value

I am dealing with a specific data structure: $scope.personalityFields.traveller_type = [ {"id":1,"value":"Rude", "color":"red"}, {"id":2,"value":"Cordial", "color":"yellow"}, {"id":3,"value":"Very Friendly", "color":"green"}, ]; Also, there is a se ...

Manipulating the DOM by nesting an icon within a button element in HTML

Currently working on my todo list project and I have a question about using innerHTML. I'm curious if I can include an icon inside of a button tag like this: btn.innerHTML = '<i class="fas fa-times fa-lg"></i>'; So, wo ...

Ensure the video plays automatically without being muted

<div class="tab-img"> <video id="autplay-video" width="320" height="240" controls autoplay poster="https://solax-prod.s3.amazonaws.com/demo/Thumbnail+English-SOLAx+Video.jpg& ...

Unable to apply 100% height to flex child element

When it comes to creating a layout for my website, I have a simple idea in mind. I want the body content to take up at least 100% of the height of the page. This setup works perfectly on desktop screens, but when I switch to a mobile view (which changes th ...

Adding navigation buttons to a Material-UI Select component: A step-by-step guide

Currently, I have integrated a Select component from MUI and it is functioning well. When an item is selected from the list, the router automatically navigates to that location: This is the snippet of code being used: export default function SelectLocatio ...

What could be causing my router UI in angular.js to malfunction?

Having an issue with routing not functioning as intended, here is the relevant code: $urlRouterProvider. otherwise('/list'); $stateProvider. state('home', { abstract: true, views: { 'header': { templateUrl: &apos ...

Best practices for consuming streams using jQuery

Looking to extract VU meter data from my shoutcast server in a continuous live stream format with the following structure: "0xa5 leftVal rightVal 0xa5 leftVal ..... etc" My goal is to capture and decipher this data using JavaScript (jQuery) for animated ...

Difficulty with Angular update: TS2339 error stating that a property is not recognized on a imported object within a JSON

Recently, I encountered an issue while upgrading Angular from version 7 to 16. The import of objects from a JSON file was functioning properly in Angular 7 but is now causing errors. Specifically, it throws the error message "TS2339: property does not ex ...

Event to discard currently selected pushpin in Bing Maps v8

There are two event styles available for a pushpin in Bing. enableHoverStyle : Boolean enableClickedStyle : Boolean To see these events/styles in action, visit the link below: My goal is to deselect an already selected pin when another pin is selected. ...