Vue.js | Dynamically add a new key and value pair to an array being built using $ajax

Currently, our goal is to implement a calendar using Vue.js where the values are fetched via an $ajax call. Following this, I aim to manipulate some of the children's data in Vue.js.

I've spent over 2 hours trying to discover a suitable method for achieving this task. However, I'm struggling to figure out how to target a property within the dynamic children of the data object.

My latest attempt involved using a '$refs' call, which somewhat accomplishes what I need. Yet, I believe I cannot effectively manipulate the children's data this way.

As of now, my Vue object looks like this:

var app = new Vue({
        el: '#aankomende-week',
        data: {
            calendar: ''
        },
        methods: {
            deleteAll(){
                app.calendar = '';
            },
            callAJAX() {
                $.post(
                    '/ajax/calendar',
                    '',
                    function (response) {
                        app.calendar = response;
                    },
                    'json'
                );
                console.log(this.$refs);
            }
        },
        created: function(){
            this.callAJAX();
        }

    });

Here is a snapshot of my template:

https://i.sstatic.net/sG8L1.jpg

And my data array looks like this:

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

Is there a way to create a new property such as:

this.calendar.events.[child].totalTime = this.calendar.events.[child].end - this.calendar.events.[child].start;

this.calendar.events.[index].totalTime = this.calendar.events.[index].end - this.calendar.events.[index].start;

this.calendar.events.[anything].totalTime = this.calendar.events.[anything].end - this.calendar.events.[anything].start;

It would be beneficial to have this implemented within a watcher so that if any values change, it recalculates the array key accordingly.

Answer №1

Assuming that the app.calendar.events is an array...

var app = new Vue({
        el: '#aankomende-week',
        data: {
            calendar: ''
        },
        methods:{
            deleteAll(){
                app.calendar = '';
            },
            callAJAX() {
                $.post(
                    '/ajax/calendar',
                    '',
                    function (response) {
                        app.calendar = response;
                        this.addNewData();
                    },
                    'json'
                );
            },
            addNewData() {
                app.calendar.events.map(function(event) {
                    event.data = 'some value';
                });
            }
        },
        created: function(){
            this.callAJAX();
        }

    });

A new method called addNewData has been included in your response. This method, part of the methods object, utilizes a map function on the events array to add a specific property for each event. The result is an array with the added property. Further details about map can be found here

Answer №2

Vue.setup( object, property, newValue )
Parameters:

{Object | Array} object

{string | number} property

{any} newValue

Returns: the updated value.

Usage:

This function adds a new property to an existing object in Vue, making sure that the new property is also reactive to trigger view updates. It's crucial to use this method when adding new properties to reactive objects because Vue cannot detect regular property additions like this.myObject.newProperty = 'hi'.

Note that the target object cannot be a Vue instance or the main data object of a Vue instance.

Vue Documentation

Answer №3

Your code has a couple of issues that need addressing

1. The ajax response value is being assigned using app.calendar, it should be done with this.calendar=response

2. Additionally, you should utilize Vue.set when adding a new property or inserting a value into an array. For more information on this topic, refer to this resource. It's important to note that Vue.set cannot be used for adding top-level 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

What could be the reason for the component failing to update even after modifying the object's properties?

I have come across some related threads on Stack Overflow, but they only briefly mention using the spread operator. But why should we use it? In the code below, I am trying to update the firstName property of the user object, which is a state, when clicki ...

Angular Directive: Enabling Form Validation for Submit Button Directive

Managing validations for multiple forms in my project has been quite challenging. Each form requires specific validation expressions, along with a loading element which complicates the reuse of buttons. To tackle this issue, I thought of utilizing a direct ...

transmitting a JSON object to the JSONResult controller in ASP.NET MVC

When I send an ajax request to my MVC controller and pass an object, it shows as null in the controller. function add() { var viftech = { "id": $("#id").val(), "name": $("#name").val(), "lastname": $("#lastname").val(), ...

What is the best way to retrieve unique elements from a mongoose database based on specific criteria?

In my Node.JS project, I have a model called Activity with certain attributes defined as follows: const Activity = mongoose.Schema({ name: { type: String, require: [true, "A activity must have a name"] }, city: { ...

Encountering type errors with ReactJS State OR Logical Operator

My component has a basic state setup, but I keep encountering the error message: TypeError: Cannot read property 'year' of undefined when using this code: export default class Login extends Component { state = { isLoading: false, event ...

Tips for enabling simultaneous input focus on both TextField and Popover components

I am working on a popover component that appears below a textfield component. The goal is to trigger a menu when the user types a specific key, like :, into the textfield. The user can then select an option from this menu to autocomplete the textfield. A ...

Deleting a record in Laravel using AJAX is a simple process that involves sending a request

Even though I have looked at similar questions about this problem and followed the suggested solutions, I am still unable to fix it. The error message I keep encountering is: BadMethodCallException Method delete does not exist. in Macroable.php (line 74 ...

Setting up React Native on a Mac M1 device

I am currently setting up React Native on my MacBook M1 Despite having installed npm, JDK, Node, Rosetta, CocoaPod, VSCode, Android Studio, Xcode and more, when I try to run the command (npm start), the directories for iOS and Android are not present. The ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

Having trouble with the ::after element in my React component for my latest React 3D portfolio project

For my portfolio project, I am following a tutorial by LamaDev (https://www.youtube.com/watch?v=qALsVa-V9qo&t=2334s&ab_channel=LamaDev). At around timestamp 36:40, he creates a ::after selector which is not working for me, even though the rest of t ...

Material UI Appbar is throwing an error with an invalid hook call

For my project, I needed to create a simple app bar, so I decided to use the code provided on the Material UI website. Here is the component's code that I used: import React from 'react'; import { fade, makeStyles } from '@material-ui/c ...

Is It Possible to Run Javascript Code Based on a Specific Screen Size?

Here is the Javascript code I'm currently using to control the mobile menu functionality on my website. It prevents content outside of the menu from scrolling when the mobile menu is open and closes the menu when an item inside it is clicked. document ...

I'm looking to center the column content vertically - any tips on how to do this using Bootstrap?

Hello! I am looking to vertically align the content of this column in the center. Here is an image of my form: https://i.stack.imgur.com/nzmdh.png Below is the corresponding code: <div class="row"> <div class="form-group col-lg-2"> ...

Checking the image loading functionality with Cypress

I am interested in testing Cypress to verify that an image is successfully loaded onto a page. Here is a snippet of my source code: import React from "react"; export default class Product extends React.Component { render() { return ( <div ...

What causes the Error: ENOENT open error to occur when attempting to render a doT.js view?

My first experience with doT.js led me to create a basic server setup: 'use strict'; var express = require('express'); var app = express(); var doT = require('express-dot'); var pub = __dirname+'/public'; var vws ...

Refreshing various innerHTML elements using a universal function

I'm attempting to consolidate several similar functions into one, but I'm encountering some challenges. Below is an example of one of the original functions that is called by a button press: function ADD_ONE(Variable_Name){ Variable_Name += ...

Changing the z-index property of a Material-UI <Select> dropdown: What you need to know

Currently, I am implementing an <AppBar> with a significantly high z-index value (using withStyles, it is set to theme.zIndex.modal + 2 which results in 1202). The primary purpose behind this decision is to guarantee that my <Drawer> component ...

Instructions for implementing a "Load More" feature on blogs using either HTML or JavaScript

When retrieving blogs from a SQL Database, some of them tend to be lengthy. To tackle this issue, I plan on trimming each blog down to around 30 words (this amount may vary) and then incorporating a Load More link at the end. This link will enable users to ...

Ways to display a targeted div element in Ruby on Rails when a limit is imposed

I'm working on a Rails app and I have a specific goal in mind. I want to automatically display a static div element only when the conditions limit(4) are met, meaning 4 div elements are showing. Essentially, I want to show the "Apply for our Program" ...

Designing a system for transiently holding data in a JavaScript framework

I am in the process of developing a JavaScript library that wraps around a third-party REST API (primarily for server-side use, but not limited to it). One of the actions defined by this API is 'login', which generates a session key required for ...