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

Update the content of the page without reloading images

Is there a way to refresh a webpage on click without refreshing the images, only the text content? Can this be achieved without clearing the cache? I attempted to refresh the entire page with the following JavaScript code: <script> $(".secon ...

What are some creative ways to incorporate images into SVG paths?

Check out my JSFiddle here. I'm attempting to position this image in the center of my arc. My initial thought was to use .attr("fill","url('somePicture')"), but so far, no luck with that approach. const width = 700; const height = 600; con ...

combine multiple keys into a single element with angular-translate

Within my application, I am retrieving translation keys from a single cell within a database table and dynamically displaying them on a settings page. While most entries will have just one key in the display object, there are some that contain multiple key ...

Click Action on CanJS Table

I am currently developing a canJS application and have been able to successfully handle the click event for an HTML table using the code below. 'table td click':function(el,event){ console.log('clicked ',el.text()); } ...

Having trouble implementing connect-busboy in my Node.js application

Currently, I'm trying to implement image uploads in my node.js application using connect-busboy. Here's the code snippet I've written based on the reference guide https://www.npmjs.org/package/connect-busboy: router.post('/upload&apos ...

How can I properly choose distinct values for an individual attribute from a JavaScript array containing objects?

Let's imagine a scenario with an array of JavaScript objects like this: var data = [ {category : "root", type: "qqqqq", value1: "aaaaa", value2: "zzzzz"}, {category : "root", type: "qqqqq", value1: "aaaaa", value2: "xxxxx"}, {category : " ...

Ways to use string functions in JavaScript to substitute with /

Here is the image path I am working with: var str = "D:\Poc\testProject\DataPush\public\unzip\cust\AccountData\2.jpg" When I included "unzip" in the path, it threw an error as shown in this image, but when ...

Tips on building a carousel with slot elements

Many people have shown me the traditional way of creating a carousel using an array of images. However, I find this method to be limiting because I want each slide of my carousel to include a lightbox component. Instead of having to rewrite the lightbox fu ...

Trouble displaying image due to issues with javascript, html, Angular, and the IMDb API integration

I have been working on displaying images from the IMDb API in my project. Everything works perfectly fine when I test it locally, but once I deploy the project to a server, the images do not load initially. Strangely, if I open the same image in a new tab ...

Leverage Vue.js variables within the index.html file

Is there a way to incorporate Vue.js variables within an index.html page? <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1.0" ...

Tips on how to bring in a module from index.js

Recently, I set up a sample node.js project: "name": "example", "version": "1.0.0", "type": "module", Let's take a look at the index.js (only two lines): "use strict"; import ...

The function and if-else statement are experiencing malfunctions

Currently in the early stages of learning coding, I've been focusing on building a solid foundation by practicing with CodeWars. Utilizing this platform for practice has been beneficial because it offers solutions for guidance. While attempting to wor ...

Sort a JSON array alphabetically in Angular.js even when there are no key/value pairs specified

I'm having trouble alphabetizing a list using a JSON array in my code. Despite my efforts, the sorting doesn't seem to be working correctly. You can view my current code by following this link to the jsfiddle http://jsfiddle.net/hxxLaxL3/ Here i ...

What is the most effective method to exhibit every element within a content wrapper at a specific interval of time?

I am looking for a way to display each div within the content-wrapper after a specific time interval. Currently, I am using individual classes like el1, el2, el3, ... to accomplish this task. However, when dealing with content-wrappers containing multipl ...

Using jQuery Datatables fnReloadAjax successfully triggers a reload of the data, however, it

In my jQuery datatable, I am utilizing the code below to refresh the data: $(".unread-rows").click( function(e) { e.preventDefault(); message_table.fnReloadAjax("/letters/ajax/inbox/1"); message_table.fnDraw(); $(this).addClass("active").s ...

Retrieve the total number of hours within a designated time frame that falls within a different time frame

Having a difficult time with this, let me present you with a scenario: A waiter at a restaurant earns $15/hour, but between 9:00 PM and 2:30 AM, he gets paid an additional $3/hour. I have the 'start' and 'end' of the shift as Date obje ...

Navigating with Buttons using React Router

Header: I need help figuring out how to properly redirect to a new page when clicking on a Material UI button using the onClick method. Specifically, I am unsure of what to include in my handleClickSignIn function. Here is a snippet of code from my Header ...

When using `setState()`, ensure that you are updating a component that is already mounted or in the process of mounting. If you receive this error, it

When using WebSocket to communicate with my server, I call the handleSubmit() function to send data and update my state based on the received response. Everything works fine initially. Upon calling componentWillUnmount, I stop sending data to the websocke ...

Is it possible to capture a screen recording in Selenium using JavaScript?

While my tests are running, I am looking for a way to record my screen. I came across a post about screen recording using Java at . However, the code provided is in Java and I require something in JavaScript. Is it possible to record the screen using Jav ...

Expecting a declaration statement for exporting React

When attempting to export my component, I encounter an error in my editor stating export declaration statement expected Here is the code snippet: export Header from './Header/Header'; However, if I modify it like this: export {default as Head ...