Dynamically update a directive array in Vue.js based on real-time changes

In my Vue project, I have an array defined in the data() method that is populated through a custom directive in its bind hook. Here's the code snippet:

import Vue from 'vue'
export default {
el: '#showingFilters',
name: "Filters",
data() {
    return {
        country: '' // connected to a <select> element
        states: [],
    }
},
directives: {
    arraysetter: {
        bind: function(el, binding, vnode) {
            vnode.context[binding.arg] = Object.keys(el.options).map(op => el.options[op].value);
        },
    },
},
methods: {
    countryChangeHandler() {
        this.states.splice(0)
        fetch(`/scripts/statejson.php?country=${this.country}`)
            .then(response => response.json())
            .then(res => {
                res.states.forEach( (element,i) => {
                    Vue.set(this.states, i, element.urlid)
                });
            })
    },
}

The issue arises when I try to re-populate the states array within the countryChangeHandler() method, triggered by the @change event on the country select tag. Even though I clear the array using splice(0) and use Vue.set for reactive re-population, Vue does not recognize the changes! However, the array contains the correct elements. I am unsure how to make it reactive.

PS: I have tried finding a solution without using forEach, but $set requires an index to work properly.

I would greatly appreciate any assistance with this.

Answer №1

This solution will efficiently handle reactivity while maintaining functionality.

  1. Replacing the entire array without resorting to using splice or set is achievable.

  2. To address potential interference with the reference to this caused by the fetch call, a closure has been implemented.

countryChangeHandler() {
        this.states = []
        const that = this
        fetch(`/scripts/statejson.php?country=${this.country}`)
            .then(response => response.json())
            .then(res => {
                that.states = res.states.map(it=>it.urlid)              
            })
    },

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 there a type-safe alternative to the setTimeout function that I can use?

When running my tests, I encountered an issue with the setTimeout method making them run slower than desired. I initially attempted to address this by using "any" in my code... but that led to complaints from eslint and others. Now, I have implemented a ...

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

Activate dual AJAX JSON and cycle through multiple alerts each time an "ul li" element is clicked

In my code, I am utilizing two ajax requests. One retrieves a chat userlist column in JSON format, while the other fetches the message history for each user. The functionality works such that when a $('.member_list ul li') element is clicked, th ...

Loading Disqus comments dynamically upon clicking a button within a Next.js application

After noticing a significant decrease in page performance scores due to Disqus comments embedded on Vercel Analytics, I am considering implementing a "Load comments" button instead of loading the actual comments onClick. I have been using the disqus-react ...

What is the correct procedure for utilizing variables in the parseJson function when working with string objects?

While working with the parseJson function, I have encountered a challenge where I need to incorporate a variable within three objects. Is there a way to merge a variable with the value of one object? Alternatively, can I utilize a third object to store t ...

Modifying the content of JSON key values

In my application, I am using MongoDB, Express, and MongoDB. When receiving data on the server side, it comes in the form of an array of objects (JSON) named upProbations. For example, let's say I find information about Max: [ { Name ...

press a cURL PHP ajax button to trigger an action

Hello everyone, I could really use some help here. I've been looking at similar questions but none of the answers seem to apply to my situation. I extracted a page using curl, however, there's a button on that page that I am unable to interact w ...

Encountering an issue with Laravel Mix and Vue where lazy-loaded components are causing an error as an unknown custom element while utilizing

I recently set up Laravel Mix and now I'm working on implementing lazy loading components in my project. I've configured the babel plugin 'syntax-dynamic-import' correctly so that the import statement in app.js is functioning as expecte ...

Troubleshooting "These dependencies were not found:" error message during deployment on Netlify, despite successful execution of yarn run serve on local machine

Currently, as I am creating a website using Vue.js, yarn, and Netlify. The build process works smoothly on my local machine when running yanr run build. However, upon deploying it through Netlify, an issue arises: 5:17:55 PM: failed during stage 'bui ...

Using Vue.js to set a mobile browser's viewport height to 100%

My webpage has a min-height: 100vh property which causes some overflow on the bottom when rendered on mobile browsers. To fix this issue, I am using the following script: methods: { calcVH() { const vH = Math.max(document.documentElement.clien ...

Node.js using Express: Modifying response data for specific route

I've searched through numerous resources but haven't been able to find a solution, so I'm reaching out for some assistance! :) I have developed a UI5 Application using Node.js with Express on the server-side. The data is retrieved from a SQ ...

Obtaining the value of an input field in HTML

I am currently working on a text input field that triggers a JavaScript function when a numeric value is entered. <input type="text" value="key" ng-keypress="submit(key)" ng-model="pager.page"/> Controller $scope.submit = function (val) { ...

Looking to alter the appearance of a div within an iframe by matching it with the title of the parent window using javascript?

I am currently working on a parent page titled Criatweb, which contains an iframe page. My goal is to modify the display of a specific div within the iframe page only when its title matches Criatweb. I attempted to implement the following script within t ...

Is it possible to create tabs using Ajax without using jQuery?

Exploring the realm of tabs that dynamically load content into a div without redirecting to another page unveils numerous possibilities. Although the existing examples mostly rely on ajax with jQuery or similar libraries, I am inclined towards exploring a ...

Searching in Vue based on the selected option is only possible by the selected criteria and not by id, regardless of the

#1 Even if chosen, cannot search by id. The 'name' condition in the loop works well but I am unable to correctly search by id (returns nothing). #2 When selecting an option from the dropdown menu, it only displays until I start typing. I would l ...

Capturing the action phase in Liferay to change the cursor to 'waiting' mode

I'm currently working on a large Liferay project and have encountered a specific issue: Whenever something in the system is loading or processing, I need to change the cursor to a waiting GIF. While this is simple when using Ajax, there are many inst ...

How can I use a JavaScript function to remove an element from a PHP array?

Imagine I have a PHP session array: $_SESSION[MyItems]=Array('A'=>"Apple", 'B'=>"Brownie", 'C'="Coin")) which is utilized to showcase items on a user's visited page. I want the user to have the ability to remove o ...

Is there a way to stop the dropdown from automatically appearing in a DropDownList?

Seeking a solution to use a custom table as the dropdown portion for a DropDownList in my project. My goal is for users to see the custom table when they click on the DropDownList, rather than the default dropdown menu. I expected to be able to achieve th ...

Set boundaries for the width and height of an image in the input field

Looking to restrict the size of an image in an input field using HTML, CSS, and JavaScript/jQuery. Goal is to maintain a perfect square aspect ratio for profile photo uploads (for example, 200x200 or 300x300). ...

Learn the process of updating database information with AngularJS through a button click

As a newcomer to Angular, I am facing an issue in my mini project. The main goal of the project is to display data from a database. I have successfully set up the view to show current data by making API calls and connecting to the database. However, I am n ...