Vue: Customize data based on userAgent

As a newcomer to VUE, I am attempting to dynamically modify the disabled value based on the userAgent in order to display or hide the paymentMethod:

data() {
            return {
                paymentMothods: [
                    { name: 'Visa checkout', img: 'visa.png', disabled: false, height: '19', class: 'v-button' },
                    { name: 'PayPal', img: 'paypal.png', disabled: false, height: '18.9', class: '' },
                    { name: 'PhonePE', img: 'phonepe.png', disabled: true, height: '18.9', class: 'phonepe' },
                ]
           }
},

If the userAgent is phonepe-webview, I am trying to adjust the value as follows:

methods: {
            phopepeMatch: function () {
                let userAgent = navigator.userAgent
                let phonepeMatch = userAgent.match("phonepe-webview")
                if (phonepeMatch === "phonepe-webview"){
                    this.paymentMothods[2].disabled = false
                    return true
                }
                else {
                    return false
                }
            }
},

Despite my efforts, the payment method remains invisible :(

Answer №1

There seems to be some confusion about what the match function actually returns. When there is a match, it returns an array and not just the string that was matched. If there is no match, it returns null. You can find more information about this here.

To address this issue, you can make the following adjustments in your code:

checkPhonepeMatch: function () {
  let userAgent = navigator.userAgent;
  let phonepeMatch = userAgent.match("phonepe-webview");
  if (phonepeMatch === null) {
    return false;
  } else {
    this.paymentMethods[2].disabled = false;
    return true;
  }
}

Answer №2

Utilize the .splice() method.

methods: {
        phopepeMatch: function () {
            let userAgent = navigator.userAgent
            let phonepeMatch = userAgent.match("phonepe-webview")
            if (phonepeMatch === "phonepe-webview"){
                // First, make a copy of the object
                let payment_method = this.paymentMothods[2];
                // Next, modify the desired property of the object
                payment_method.disabled = false;
                // Finally, replace the old object with the updated one
                this.paymentMothods.splice(2, 1, payment_method);
                return true
            }
            else {
                return false
            }
        }

},

Additional details:

In the Vue documentation, specifically in the Reactivity in depth section, it mentions:

Vue cannot automatically detect the following array changes:

1.) Directly setting an item using the index, e.g., vm.items[indexOfItem] = newValue

2.) Changing the length of the array, e.g., vm.items.length = newLength

However, there is a way to handle this so that Vue's Reactivity System can recognize alterations in arrays.

Instead of doing this:

this.paymentMothods[2].disabled = false

You should follow this approach:

let payment_method = this.paymentMothods[2];

payment_method.disabled = false;

this.paymentMothods.splice(2, 1, payment_method);

or alternatively (using this.$set()):

let payment_method = this.paymentMothods[2];

payment_method.disabled = false;

this.$set(this.paymentMothods, 2, payment_method);

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 is the process for using Discriminators, the Mongo DB API, and Mongoose to insert data into Cosmos DB?

Issue Overview I am currently facing a challenge in writing documents to my Cosmos DB using the Mongo DB API and Mongoose for Object Modeling. To optimize costs, I aim to store all documents in a single collection by utilizing Discriminators. The project ...

Stop users from signing up if the chosen username is already in use

I have a script that successfully checks if a username is available, but even if the username is already taken, the user can still register. I am looking for a way to prevent registration if the username is not free. Here is the code snippet: index.php $ ...

Troubleshoot my code for clustering markers on a Google map

I'm currently working on a piece of code to generate a Google map that contains 3 hidden points within one marker. The idea is that when the main marker is clicked, these points will either merge into one or expand into 3 separate markers. However, I& ...

What is the best way to adjust and filter an array based on a single value?

Here is an array that needs to be modified: [ {name: "test", value: "test", group: 0}, {name: "test1", value: "test2", group: 0}, {name: "test3", value: "test3", group: 1}, {name: "te ...

Switch between two functions by clicking a button

Presented here is a button that serves as a toggle switch: <button ng-click="togglefunction()">Toggle Data</button> Below is the toggle functionality: $scope.toggleToolPanel = function () { // The goal is to include the following 2 ...

Retry request with an AngularJS interceptor

Currently, I am in the process of developing an Angular application and encountering some challenges while implementing a retry mechanism for the latest request within an HTTP interceptor. The interceptor is primarily used for authentication validation on ...

Is there a way for me to show "No data" when the json response in vue js is empty?

Is it possible to display a message like "No search results" when there is no data available? I am new to this and only have basic understanding. Can someone guide me on how to achieve this? Example of my JSON data when it's empty: { "status": true ...

Automatically populate the article number field once the article name has been entered

I am currently working on a HTML <form> using PHP. Within this form, there are three <input> fields. The goal is to have the second <input> field automatically populate once the first one is filled out. This will involve triggering an HTT ...

Generate dynamic forms utilizing JSON data

I am in the process of developing an application that enables users to answer questions about themselves. The questions are being retrieved from an API. My next step is to generate a form with these questions as entry fields. I am currently utilizing a met ...

Tips for including a JSON file within the utils directory of a Node.js project

I have a JavaScript file located in the utils folder of my Node.js project. This JS file is responsible for retrieving data from a database. However, at the moment, I only have mock data stored in a local JSON file. Now, I need to figure out how to load th ...

Using JavaScript, extract current date from an API data

Here is an example of how the data from my API appears: const data = [{ "id": "1", "name": "Lesley", "creationDate": "2019-11-21 20:33:49.04", }, { "id": "2", "name": "Claude", "creationDate": "2019-11-21 20:33:09.397", }, { "i ...

Troubleshooting issues with adding child elements in JavaScript

Styling with CSS: ul #allposts li{ height: 50px; width: 50px; background-color: yellow; border: 1px solid yellow; } Creating HTML structure: <ul id = "allposts"></ul> Adding JavaScript functionality: var container = documen ...

Activate the action using the onclick interaction

window.addEventListener(mousewheelEvent, _.throttle(parallaxScroll, 60), false); My current setup involves an event listener that responds to a mousewheelEvent by executing a function. However, when attempting to directly trigger this function on a separa ...

There was a failure to establish a Redis connection to the server with the address 127.0.0.1 on port 6379

Currently, I am working with node.js using expressjs. My goal is to store an account in the session. To test this out, I decided to experiment with sessions by following the code provided on expressjs var RedisStore = require('connect-redis')(ex ...

What is the purpose of using a callback like "function(value) {return my_function(value);}" in node.js programming?

Hello, I am brand new to JavaScript so please bear with me if my question seems too simple. Let's say I have a list of strings and I want to filter them based on a function f that takes a string as input and returns a boolean. This approach works: f ...

Roundabout Navigation Styles with CSS and jQuery

My goal is to implement a corner circle menu, similar to the one shown in the image below: https://i.stack.imgur.com/zma5U.png This is what I have accomplished so far: $(".menu").click(function(){ $(".menu-items").fadeToggle(); }); html,body{ colo ...

Adjust dropdown options based on cursor placement within textarea

I have a textarea and a dropdown. Whenever a user selects an option from the dropdown menu, it should be inserted into the text area. However, I am facing a bug where the selected value is being inserted at the end of the text instead of at the current cur ...

Experiencing a "non-serializable value found in the state" error specifically while utilizing redux toolkit, but this issue does not occur with traditional redux implementations

While transitioning my app to utilize Redux Toolkit, I encountered an error after switching over from createStore to configureStore: A non-serializable value was found in the state at path: `varietals.red.0`. Value:, Varietal { "color": "red", "id": " ...

Executing a function within a VueJs 2 component immediately after it has finished loading

How can I retrieve data after a component has finished loading? When I initialize my Vue instance and load the component, the template loads correctly but the functions in the mounted lifecycle hook are not executed, causing the stats object to remain empt ...

Working with Vue.js: accessing nested data from child components within a v-for loop

When working with a v-for loop, my goal is to group every 4 results retrieved from the API into a single row. <div v-for="(item, index) in this.info.length/4" :key="item"> <el-col v-for="thing in this.info" :key="thing"> {{ thing }} ...