I'm having trouble passing a value to my parameter in Vue code. Can anyone help me figure out what's going wrong

Whenever I look at my code, the parameter dbtask is consistently showing up as null.

If we navigate to , we can see the data displayed below:

[{"idknowledgedescription": null, "idexercise": null, "answerpath": "浙江数学文testpdf.pdf", "value": null, "iddailytask": 1, "briefanswer": "A", "time": null, "idstudents": 1, "exercisepath": "浙江数学文testpdf.pdf", "timeofplan": "2018-03-15", "timeoflearn": "2018-03-15T00:00:00", "anserofstudent": null, "tipspath": "浙江数学文testpdf.pdf"}]
<!DOCTYPE html>
{% load static %}
<html>
  <head>
      <meta charset="utf-8"/>
      <script src="{% static 'jslib/vue.js'%}"></script>
      <script src="{% static 'jslib/reqwest.js'%}"></script>
      <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

    <link rel="stylesheet" href="{% static 'css/semantic.min.css'%}" media="screen" title="no title" charset="utf-8">
  </head>
      <body>
     {% verbatim %}
        <div id="app-6">

               <li v-for="t in  dbtask">
                {{t.exercisepath}}
            </li>

         </div>
      {% endverbatim %}

      </div>


      </body>
</html>
    <script type="text/javascript">
    var app6 = new Vue({
      el: '#app-6',
      data: {
         dbtask:null,
      },
      created() {
          setTimeout(() => {
            this.bbb()
          }, 1000);
      },
      methods: {
        bbb: function() {
            var self=this;
            <!--var a={};-->
             $.getJSON('http://127.0.0.1:8000/tasks/',function(task){
                          self.dbtask = task;
                          alert(self.dbtask[0].exercisepath);
                        });

        }.bind(this)
      }
    })
  </script>

`

Answer №1

Make sure to remove the .bind(this) from your method declaration. If you keep it, the method function will be bound to the window object instead of the Vue instance.

To clarify, if you have

methods: { myMethod: function() { console.log(this); }.bind(this) }
, the this inside myMethod will refer to window and not the Vue instance.

Check out this quick demo:

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    regularMethod: function () { console.log('regular method', this.message); },
    bindThisMethod: function () { console.log('method with .bind(this)', this.message); }.bind(this)
  },
  created() {
    this.regularMethod();
    this.bindThisMethod();
  }
})
<script src="https://unpkg.com/vue@latest/dist/vue.min.js"></script>

<div id="app">
  <p>{{ message }}</p>
</div>

Finally, remember to adjust your code like this:

  methods: {
    bbb: function() {
        var self=this;
        <!--var a={};-->
         $.getJSON('http://127.0.0.1:8000/tasks/',function(task){
                      self.dbtask = task;
                      alert(self.dbtask[0].exercisepath);
                    });

    // }.bind(this) // remove this
    }               // should be like this
  }

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

JS not functioning properly in specific pages causing display issues with page height set to 100%

I am facing an unusual issue where certain pages do not stretch to 100% page height in the middle section, causing the left-hand border to be incomplete. For example, on the 'Brentwood' site (please click on the 'Login' link in the top ...

Unlocking the potential of GraphQL: Harnessing the power of sibling resolvers to access output from another

Could use a little assistance. Let's say I'm trying to retrieve the following data: { parent { obj1 { value1 } obj2 { value2 } } } Now, I need the result of value2 in the value1 resolver for calculation ...

What can be done to enhance this particular element?

I've created a Component that uses a 3rd party joke API to fetch jokes with a specific category upon page load. The component also includes a refresh button for fetching new jokes. export default function Jokes() { const { cat } = useParams(); const [ ...

Guide on dynamically displaying a page based on the response from express/mssql middleware

I have developed a full stack application that includes a registration feature which successfully adds data to the database. Now, I am looking for a way to conditionally display the home page based on whether the login credentials are correct. Within my l ...

Interact with a webpage element using Selenium

My goal is to extract information from the following page: I want to interact with each blue stats icon on the page (one for every match of the tournament). Below is the code I am using: from selenium import webdriver from selenium.webdriver.common.by im ...

Using Set in combination with useRef: A Beginner's Guide

Trying to implement Set with useRef. Below is my attempt. export default function App() { const data = useRef<Set<string>>(new Set()); const add = () => { data.current = new Set([...Array.from(data.current), ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

404 Response Generated by Express Routes

Exploring the MEAN stack has been a great way for me to expand my knowledge of node and express. Currently, I am working on creating a simple link between two static pages within the app. My routes are set up as follows: //Home route var index = require( ...

Various activities tailored to the amount of clicks

I've encountered some difficulties trying to achieve a specific functionality: https://jsfiddle.net/CreativeAU/ys12ed05/ warningbutton.onclick = function buttonClicks() { count += 1; if (count > 1) { window.location.href = "http://www.google.com. ...

Issue with ThreeJS AdditiveBlending, ShaderMaterial, and DepthTest

As I work on creating a scene with a variety of objects, I drew inspiration from a CodePen example by gnauhca (https://codepen.io/gnauhca/pen/VzJXGG). In the example, DepthTest is disabled on the ShaderMaterial, but I actually need it to be enabled in orde ...

Creating an HTML Form that Sends an Email

I'm completely stumped as to where the issue lies! The mail() function is working perfectly fine (I tested it with a simple PHP file), but for some reason, my form isn't sending any emails! HTML <section id="contact"> <div id="go ...

The Django CSRF token is inaccessible for retrieval

I'm in the process of developing a website using Vue.js for the frontend and Django for the backend. I've made sure to include the csrf token in every request from the frontend to the backend to prevent any 403 Forbidden errors. All requests are ...

Create a d3 map specifically for a selected region based on the provided latitude and longitude coordinates

I am currently working on developing a d3 map inspired by the codepen created by Andy Barefoot: https://codepen.io/nb123456/pen/zLdqvM?editors=0010. My goal is to adjust the initiateZoom() function in a way that setting specific lat/lon coordinates for a b ...

Discover the process of linking a JavaScript file to an HTML file in React

I am trying to render a React JS file that contains the following code: React.render( <TreeNode node={tree} />, document.getElementById("tree") ); I have included this file in an HTML document like so: <!doctype html> <html lang=" ...

The essential criteria for script tag and page validation requirements

There are instances where I have pages that contain only a script without any content (such as sending data through postMessage and then closing itself). In these cases, is the page considered valid with just <script>doSomeStuff</script> or do ...

Updating data in Redux triggers a refresh of Material UI table data

Utilizing the material-ui data table component to showcase data, enabling users to update and save information via a form when clicking on a row. Implemented react-redux for state management and dispatching updated rows to the existing data. However, despi ...

Developing a script using Browserify results in generating a file with no content

I recently created a build script with the intention of combining all my JavaScript modules into a single file using browserify. The code I used was inspired by a post I found at . function _browserify(srcPath, distPath) { var browserify = require(&apos ...

What are the ways to prolong or pause the JSON transformation process in NodeJS?

I'm currently extracting keywords using ExpressJS: /* * GET keywords. */ router.get('/keywords', function(req, res) { // Ensure user is logged in if (req.user) { var db = req.db; var user = req.user; db.col ...

Issue with back button functionality when loading page with history.pushState in JavaScript

My current issue involves loading a page via ajax using history.pushState. The page loads successfully, but the back button does not work as expected. I have included my code below for reference: function processAjaxData(response, urlPath){ document.wr ...

Personalized labels for your JQuery Mobile sliders

Struggling to make this work correctly, I aim to introduce tick marks and custom labels into jQuery Mobile's slider widget. My goal is to add tick markers at 0, 25, 50, 75, and 100 with a unique string above each tick. Additionally, I want these label ...