Utilizing VueJS to incorporate data retrieved from query parameters

I am currently developing a compact VueJS application that operates solely on the client-side. The application utilizes VueRouter to update the URL when users input data into the app. This allows users to refresh the page and reload their data by using the URL. The data is stored in query parameters, for example:

.../app.html#/?time=300&time=300&distance=300&distance=300&unit=m&unit=m

The data is appropriately parsed through the router. However, when I try to add the data to my empty performance array, I encounter a problem with the :class attribute in the markup causing:

TypeError: Cannot read property 'length' of undefined

The error points towards the performances array being undefined within the :class attribute located inside the v-for performance loop. By removing the :class from the app's markup, the site renders successfully. I suspect that the performances data array has not been properly passed to the :class.

In the VueRouter documentation, there was no mention of this specific routing issue. How can the data from the URL query parameters be effectively passed into the application? Below is a condensed version of my relevant code:

// js file
var router = new VueRouter({}); // left empty due to no routes, only query parameters are utilized

var app = new Vue({
    el: '#app',
    data: function() {
        return {
            performances: [],
            units: units,
            newPerformance: {
                distance: {
                    value: '',
                    units: units.distance.options[0]
                },
                time: {
                    formatted: '',
                    value: ''
                },
            editingPerformance: null,
        }
    },
    router: router,
    watch: {
        performances: {
            handler: function() {
                this.drawChart();
                this.updateURL();
            },
            deep: true
        }
    },
    updateURL: function() {
        var times = this.performances.map(function(v) {
                return v.time.value
            }),
            distances = this.performances.map(function(v) {
                return v.distance.value
            }),
            units = this.performances.map(function(v) {
                return v.distance.units.value
            });
        router.push({
            query: {
                time: times,
                distance: distances,
                dunit: units
            }
        });
    }
    ....
});

HTML file

...
<div v-for="(performance, index) in performances" :class="{'card-list': performances.length > 1 }">
...
</div>
...

After going through the Reactivity in Depth docs, I attempted solutions such as:

Vue.nextTick(function() {
    this.performances.push(performance);
})

and

Vue.set(app, 'performances',performanceArray);

both resulting in the same error message. Additional code snippets can be provided upon request.

Edit: Including stack traces:

[Vue warn]: Error when rendering root instance: warn @ vue.js:513
Vue._render @ vue.js:2934
(anonymous function) @ vue.js:2335
get @ vue.js:1643run @ vue.js:1712
flushSchedulerQueue @ vue.js:1530
(anonymous function) @ vue.js:465
nextTickHandler @ vue.js:414

this error followed immediately by:

vue.js:427 TypeError: Cannot read property 'length' of undefined(…)
logError @ vue.js:427

Answer №1

It appears that the issue may lie in changing the variable type of your array within your code. When you initially created it, it was defined as an array and using .length with arrays and strings is valid. However, if you change it to an object, JSON, or anything else, it will throw an error. To ensure that "this" is properly carried over in Vue.nextTick's callback function, assign it to a variable within the same scope.

var self = this;

//inside nextTick

self.performances.push(performance);

You may not necessarily need to use nextTick as it updates after the DOM has been re-rendered. Using push() triggers a new DOM rendering, improving responsiveness. Waiting for nextTick could delay updates until further changes are made.

<div v-if="performances.length" v-for="(performance, index) in performances" 
:class="performances.length > 1 ? 'card-list' : ''">
...
</div>

The v-if attribute ensures content is only rendered when present.

This should address the issue at hand.

For further insight into the object contents, try {{ performance }} and consider using Chrome's vue-debugger extension for real-time monitoring of data properties.

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

Is it possible for an AJAX call to fail, despite receiving a valid 200OK response?

There are times when the server responses return a 200OK status, but the content of the response is not what was anticipated. Is it possible to invoke the jquery ajax error callback even with a successful response, depending on certain criteria within the ...

Invoke cloud functions independently of waiting for a response

Attempting a clever workaround with cloud functions, but struggling to pinpoint the problem. Currently utilizing now.sh for hosting serverless functions and aiming to invoke one function from another. Let's assume there are two functions defined, fet ...

Updating a view in AngularJS when an object is modified outside of its scope can be achieved by implementing certain techniques

I need help with accessing an object outside the AngularJS scope. The object looks something like this: obj = { isBig : true, name: "John" ... } This object was created and updates outside of the angular scope, for example, via an ajax call made with jQu ...

`The post route in the Express app is encountering an issue where req.body is not

Here is my router config: router.post('/', async(req, res) => { const posts = await loadPostsCollection() await posts.insertOne({ text: req.body.text, createdAt: new Date() }) res.status(201).send() }) An error has occurred in the ...

Re-calculating with Jquery when input is updated

I am looking for guidance on how to make the calculator recalculate based on a change in the #calcTotal input field. I have successfully calculated all fields and managed to update the #cwac field when one of the values before it changes. Here is the HTML ...

Exploring asp.net client-side routing using the power of page.js

Currently, I am working on constructing a basic asp.net application using webforms and my goal is to manage routing in the client. Essentially, this will be a Single Page Application (SPA). To handle the routing aspect, I have opted to utilize the page.js ...

I am finding the module.export feature in Express JS to be quite perplex

I recently started learning Express JS with the EJS templating engine, using express-generator to set up my project. I only made a few modifications to the initial code. In the directory structure of my app: MyApp->routes->index.js var express = re ...

Utilizing JavaScript Event Listener to Identify the Relevant PHP File for Display

I have incorporated two separate PHP files in my code: tabs.php accordion.php Both files iterate through the same dataset, but present the information in different ways. The choice between displaying tabs or accordions depends on the user's screen s ...

Iterate through the xml.documentElement in a loop

I want to show 8 men and 2 women in SVG format. However, my current function only displays one man and woman. How can I add a loop to make this work for all individuals? for (i = 0; i < Serie[n].Number; i++) { return xml.documentElement } The data arr ...

What is the best way to design a filter that can extract the specific card from the JSONArray collection?

I am struggling to figure out how to implement a filter that can retrieve the desired card from an array based on button selections from another JSON array. The goal is to match the value of the clicked button with a corresponding value in a separate arr ...

Share optional elements of array with props

Imagine having a component that iterates through items in an array without specifying fields. It works fine in this scenario. However, what if you want to use the same component with an array containing different fields? Is there a way to instruct the comp ...

What is the functionality of an Angular service that retrieves an

It appears that Angularjs services are constructed by passing in a Contructor function: app.service('serviceName', function(){ this.var1 = 'foo'; this.method1 = function(){ } }); Angular executes this function using the new ...

Vue.js is utilizing a JavaScript file for routing purposes to serve as the main index

I have encountered an issue with including JavaScript files globally in my web page. When I include the script ./js/my-file.js in index.html, I receive this error in the console: Uncaught SyntaxError: Unexpected token '<' If I try to access ...

Invoke a C# function (WebMethod) using Javascript (JQuery)

Having a function setup like this [WebMethod] public static string Hello() { return "hello"; } I am attempting to call it on my aspx page using the following approach function sendData(){ $.post("Default.aspx/Hello", ...

Mapping the Way: Innovative Controls for Navigation

Currently, I am utilizing the HERE maps API for JavaScript. However, I would like to customize the design of the map controls similar to this: Below is an example for reference: HERE EXAMPLE Is it feasible to achieve this customization? ...

How to efficiently manage multiple INSERT, SELECT, and UPDATE operations in mysql2 using nodejs

I am seeking guidance on how to approach a specific problem that I am facing. Due to my limited knowledge of databases, I am unsure of the best method to tackle this issue. The challenge I am dealing with involves receiving a 'large' amount of d ...

"Hidden panels in Sencha Touch only respond to show() and hide() methods after a resize event

Check out this demonstration of a Sencha Touch app by visiting this link. The button located in the bottom-left corner is supposed to show or hide the menu panel on top of the "Location info goes here" bar, but it seems to be functioning in an unexpected m ...

The AJAX request fails to execute once the webpage has finished loading for the first time

Hey there! I have a button group where the selected button triggers an ajax call. Check out the code below: <div class="btn-group" id="graphSelection"> <button type="button" class="btn disabled btn-info" id="post" onclick="graphSelec ...

What is the process for receiving user input and appending it to an array in JavaScript?

I'm currently working on a page that takes user input, adds it to an array, and then creates a select and option list from that array. <!DOCTYPE> <html> <head> <script> var optionList = []; for (var i = 0; i < optionList. ...

Breaking down a string and then retrieving elements from an array

Just diving into the world of Javascript and jQuery, so I have a simple query. I've got a date that I need to break down into a string and then display it as an array. var date = "12/10/2010"; var dateArray = date.split(/); $('#printbox') ...