Vue2: when passing a function as a prop, a warning will be triggered indicating that the prop has

As a newcomer to Vue, I've been enjoying working with Single File Components. Before diving into my main project idea, I decided to experiment with some small components to get a better grasp of the concept.

One such experiment involved creating a component for handling XMLHttpRequests with a progress bar:

https://i.stack.imgur.com/QG15q.png

<template >
  <div  v-if="showQ">
    <div class="text-muted">
      <span>{{humanReadableLead}}</span>
      <span :class="'text-'+color">{{humanReadableMessage}}</span>
      <span>{{humanReadableEnd}}</span>
    </div>
    <div class="progress">
      <div
        class="progress-bar progress-bar-striped progress-bar-animated"
        :class="'bg-'+color"
        role="progressbar"
        :style="{width: String(percent)+'%'}"
        :aria-valuenow="percent"
        aria-valuemin="0"
        aria-valuemax="100"
      ></div>
    </div>

    <div class="text-right text-muted form-text text-small">
      <span class="float-left">{{xhrMessage}}</span>
      <span
        class="badge"
        :class="'badge-'+color"
        data-toggle="tooltip"
        data-placement="right"
        :title="readyStateTooltip"
        >
          {{xhr.readyState}}
        </span>
      <span
        class="badge"
        :class="'badge-'+color"
        data-toggle="tooltip"
        data-placement="right"
        :title="statusTooltip"
      >
        {{xhr.status}}
      </span>
      <span
        v-if="transferComplete"
        @click="goodbye"
        class="badge badge-secondary"
        data-toggle="tooltip"
        data-placement="right"
        title="Dismiss progress bar"
      >
        &times;
      </span>
    </div>
  </div>

</template>

<script>

import {httpStatusCodes, httpReadyStateCodes} from './http-responses';

export default {
  props: {
    method: {
      type: String,
      default: "GET",
      validator: function(value) {
        return ["GET", "POST", "PUT", "DELETE"].includes(value)
      }
    },
    url: {
      type: String,
      required: true
    },
    async: {
      type: Boolean,
      default: true
    },
    success: {
      type: Function,
      default: function() {
        console.log(this.xhr.response)
      }
    },
    readystatechange: {
      type: Function,
      default: function(event) {
      }
    },
    automaticCloseQ: {
      type: Boolean,
      default: false
    }
  },
  data: function() {
    return {
      xhr: new XMLHttpRequest(),
      httpStatusCodes:httpStatusCodes,
      httpReadyStateCodes:httpReadyStateCodes,
      color: "primary",
      percent: 0,
      humanReadableLead: "",
      humanReadableMessage: "",
      humanReadableEnd: "",
      xhrMessage: "",
      showQ: true,
      completeQ: false
    }
  },
  computed: {
    readyStateTooltip: function() {
      var rs = this.xhr.readyState,
      rsc = httpReadyStateCodes[rs]
      return `Ready state ${rs}: ${rsc}`
    },
    statusTooltip: function() {
      var s = this.xhr.status
      // s = s == 0 ? 218 : s
      var sc = httpStatusCodes[s]
      return `Status ${s}: ${sc}`
    },
    transferComplete: function() {
      return this.completeQ
    }
  },
  methods: {
    open: function() {
      this.xhr.open(this.method, this.url, this.async)
    },
    send: function() {
      this.xhr.send()
    },
    goodbye: function() {
      this.showQ = false
    }
  },

  created: function() {
    var that = this
    that.open()

    that.xhr.addEventListener("error", function(event) {
      that.color = "danger"
      that.xhrMessage = "An error has occurred."
    })

    this.xhr.addEventListener("progress", function(event) {
      if (event.lengthComputable) {
        var percentComplete = event.loaded / event.total * 100;
        that.percent = percentComplete
      } else {
        that.percent = 100
        that.xhrMessage = "Unable to compute progress information since the total size is unknown."
      }
    })

    that.xhr.addEventListener("abort", function(event) {
      that.color = "danger"
      that.xhrMessage = "The transfer has been canceled by the user."
    });

    that.xhr.addEventListener("load", function(event) {
      that.color = "success"
      that.xhrMessage = "Transfer complete."
      that.completeQ = true
      if (that.automaticCloseQ) { that.showQ = false }
      that.success()
    })

    that.xhr.addEventListener("readystatechange", function(event) {
      that.readystatechange(event)
    })

    that.send()
  }
}
</script>

<style scoped>
</style>

In your index.html:

<div id="request" style="width:50%;" >
  <http-request :url="'./<some-file>'"/>
</div>

Using JS:

var progress = new Vue({
  el: '#request',
  components: { httpRequest }
})

This setup works quite well, but there are a few minor bugs that have me stumped:

  • I attempted to define a function onSuccess to pass as the success prop, but it resulted in an error from Vue
  • The computed property for statusTooltip does not update as expected
  • Setting automaticCloseQ always defaults to its initial value, regardless of how I try to bind it

For example:

var onSuccess = function() {console.log('here')}

<http-request :url="'./<some-file>'" :success="onSuccess" :automaticCloseQ="true"/>

What could I be missing here?

Answer №1

Thank you for taking the time to read this.

I am facing an issue while trying to define a function onSuccess that I pass to the prop success in Vue. It seems to be throwing an error.

It appears that onSuccess is being defined outside of Vue, when it should actually be defined within Vue's methods


I am having trouble with updating computed properties for statusTooltip.

In Javascript, objects are passed by reference, which means that xhr always points to the same object. This can cause issues with updating computed values. For more information, please refer to https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats. One solution could be to create another reactive data called xhrStatus and manually update this status within the xhr's event listeners.


I am struggling to set automaticCloseQ as it keeps reverting to the default value despite my attempts to bind it differently.

(This statement is unclear...)

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

Express.js not redirecting to Angular route, app not starting

I have the following setup in my node.js app.js: app.use('/', routes); app.get('some_api', routes.someApi); app.use(function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); Additio ...

How can I implement a jQuery popup that prompts users to log in or register if they are not currently authenticated?

My JavaScript code includes jQuery and AJAX functionality for a specific action. Whenever a user id is not provided, and there isn't one stored in the session, I aim to prompt the user with a dialog box asking them to either register or log in. Could ...

Having trouble with adding an event listener on scroll in React JS. Need assistance in resolving this issue

I'm having trouble adding an event listener for when a user scrolls in my web app. componentDidMount = () => { let scrollPosition = window.scrollY; let header = document.getElementById("topBar"); window.addEventListener(&ap ...

Each time the Angular children component is reloaded, the user is redirected to localhost:4200

In my Angular project, I encounter an issue with route parameters in children components. While navigating to these child components from the parent is seamless, reloading the child component causes the application to redirect to localhost:4200 and display ...

What sets apart getStaticProps + fallback:true from getServerSideProps?

I have gone through the Next.js documentation multiple times, but I am still struggling to grasp the difference between using getStaticProps with fallback:true and getServerSideProps. From my understanding: getStaticProps getStaticProps is rendered at b ...

Converting a JavaScript variable into PHP using ajax: A comprehensive guide

Can someone please help me troubleshoot this code for passing a JavaScript variable to PHP? It doesn't seem to be working properly. I want to extract the value of an ID from JavaScript and send it over to PHP. <!DOCTYPE html> <html> ...

Iterate over the HTML elements within a class and retrieve a specific property in JSON

Currently, I am in the process of developing a straightforward application that involves making an Ajax request to retrieve a Json object and then passing it to an HTML document. Essentially, this application functions as a vending machine where the produc ...

How can I integrate NIB into a project created with WebStorm 8 using node.js, Express, Jade, and Stylus?

Starting off with node.js, Express, Jade, Styl and NIB in WebStorm 8 has been a bit of a challenge. Unfortunately, WebStorm does not natively support NIB, so I have been looking into how to manually add it. Here is the sample app.js generated by WebStorm: ...

Display or conceal child links using JQuery based on their availability

I have a query regarding JQuery. If I click on Link1, which does not contain any ul.children, the class current_page_item will be added (not shown in this code as it is added automatically by Wordpress). In this scenario, the ul.children in Link2 should be ...

Display the number of likes without having to refresh the page

On my website, there is a like/unlike post feature. When I click the like button, I want the value of check2 to appear next to the like button without needing to refresh the page. Currently, after clicking like, the data is inserted but only appears after ...

Update your mappings for the city of Istanbul when utilizing both TypeScript and Babel

Currently, I am facing the challenge of generating code coverage for my TypeScript project using remap Istanbul. The issue arises due to the usage of async/await in my code, which TypeScript cannot transpile into ES5 directly. To circumvent this limitation ...

Transform this color matching game into an image matching game using JavaScript and jQuery

I have a color matching game that I would like to enhance by matching background-images instead of just background-colors. However, I am facing difficulties in making this change. For instance, instead of matching the color red with the text "red," I wan ...

Is there a way to print an HTML page in Landscape mode within my Vue.js project?

I have been able to successfully print an HTML page in Landscape mode using the code below. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,maximum-scale=1.0"> ...

What is the method for setting and comparing collectionsjs equality?

I'm interested in utilizing the data structure. Within the factory method, you have the opportunity to specify equals and compare parameters: SortedMap(entries, equals, compare). Can anyone provide insight into what the expected formats for these pa ...

What strategies can I implement to improve the performance of this Vue checktree composable during refactoring?

I am currently working on creating a Vue 3 composable to build a headless recursive checkbox tree view. The checktree is designed to only select leaf nodes, with the state of internal nodes being determined by the number of selected leaf nodes. If you wan ...

Create an object with an asynchronous function/promise declaration

I have a function that returns an object with different functions that I can use. I want to incorporate promises into these functions for better asynchronous handling. var DATABASE = (function () { var exports = {}; exports.query = function(filter = ...

Node.js - Retrieving POST request parameters and directing users in an Express application

I encountered this specific issue while setting up a post endpoint for my nodejs CLI script that utilizes express to handle requests. app.use( express.static( path.format({dir: __dirname, base: 'client/dist'})) ); app.use( express ...

Guide on setting a property for req.session

I'm a beginner in node.js and sessions, and I am having trouble setting properties to the session! I am trying to add a property to the session and save it in the database, but I keep getting errors. Here are my codes: app.js (main js file) const s ...

Chrome Extension to Emphasize Every Word

As a novice, I am embarking on the journey of creating my own chrome extension. The idea is to design a popup.html file that showcases a "highlight" button. The functionality would involve clicking this button to highlight all words on the page. Here&apos ...

What is the best way to pause function execution until a user action is completed within a separate Modal?

I'm currently working on a drink tracking application. Users have the ability to add drinks, but there is also a drink limit feature in place to alert them when they reach their set limit. A modal will pop up with options to cancel or continue adding ...