How to access Vue props using plain JavaScript

Implementing Stripe into my application has been a smooth process so far, following the plain JS examples in the Stripe documentation. However, I've encountered an issue with accessing props from the parent component within the Script tag where I make the API calls.

I've experimented with using the mounted method to ensure that the HTML has rendered before implementing the JavaScript code, as suggested by some parts of the Stripe documentation. But I'm still struggling to get it working properly. Any suggestions on how to resolve this would be greatly appreciated.

One approach I tried was putting the API call inside a method and triggering that method with a click event on the form. Unfortunately, this resulted in an error related to the 'token' used by Stripe not being recognized.

In the code snippet below, you can see where I attempted to access 'this.plan' from the props:


    <template>
  <form method="post" id="payment-form">
    <!-- Form elements here -->
  </form>
</template>

<script>
  // Import necessary modules and set up variables
  
  export default {
    props: ['plan'],
    data: function() {
      return {
        successful: false,
        monthly: {
          id: 'prod_Flp17jVPzNUfFz',
          price: 25
        },
        annual: {
          id: 'prod_Flp17jVPzNUfFz',
          price: 215 
        }
      }
    },
    methods: {
      submitPayment: function () {
        // Logic for submitting payment
      }
    },
    mounted() {
      // Code for setting up Stripe Elements and handling form submission
    }
  }
</script>

Answer №1

The issue at hand here is related to scoping. When attempting to access this.plan, the reference of this points to the callback being executed from the event listener. To circumvent this problem, it is necessary to declare a variable that holds the Vue instance in order to access these fields within any method:

mounted() {
  var vm = this;
  // Instantiate a new card Element.
  let card = elements.create('card', {style: style});

  // Mount the card Element into the 'card-element' <div>.
  card.mount('#card-element');

  // Handle real-time validation errors from the card Element.
  card.addEventListener('change', function (event) {
    let displayError = document.getElementById('card-errors');
    if (event.error) {
      displayError.textContent = event.error.message;
    } else {
      displayError.textContent = '';
    }
  });

  // Handle form submission.
  let form = document.getElementById('payment-form');
  form.addEventListener('submit', function (event) {
    console.log(event);
    event.preventDefault();

    stripe.createToken(card).then(function (result) {
      if (result.error) {
        // Notify the user in case of an error.
        let errorElement = document.getElementById('card-errors');
        errorElement.textContent = result.error.message;
      } else {
        // Pass the token to your server.
        stripeTokenHandler(result.token);
        return result.token
      }
    }).then(function (result) {
      console.log(result);
      axios({
        method: "POST",
        url: '/api/checkout',
        headers: {
          Authorization: `Bearer ${authService.idToken}`,
        },
        data: {
          subscription: result.id,
          plan: vm.plan     <----------------------------------- not working
        },
      }).then(function (res) {
        // alert("It went through! How? ")
      }).catch(function (err) {
        console.log(err)
      });
    });
  });

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

Potential 'undefined' object detected in Vuex mutation using TypeScript

Currently, I am diving into learning Vue.js alongside Vuex and TypeScript. While working on my application, I encountered an error stating "Object is possibly 'undefined'" within the Vuex Store. The error specifically arises in the "newCard" mut ...

JavaScript navigation vanishing problem

Currently, I am assisting a friend who works at a legal firm in making some modifications to his website. The website has a navigation bar on the left side that displays a submenu when hovered over. Unfortunately, he attempted to remove one of the submenu ...

Is there a way to display the form values on the table once it has been submitted?

I'm struggling with my form input not showing up under the table headings after submission. I've reviewed the code multiple times, but can't figure out what's causing the issue. If you have any suggestions on how to write the code more ...

Dynamic population of select options in Vue.js can be achieved by dynamically

I am currently working on a Vue.js application that includes a form with a drop-down menu. The options in the drop-down menu should be populated from a rest call eventually. However, I am currently using a hardcoded list: <template> <ModalForm v ...

What is the best way to include a component within a content-editable div in Vue.js?

Looking for the correct way to add a div inside a content-editable div on a click of a button in vue js. Here's the code I have been experimenting with: var ComponentClass = Vue.extend(AddTag) var instance = new ComponentClass({ propsData: { type: ...

Implement automatic calculation by utilizing ajax to fetch values from the database whenever there is a change

I am completely lost on how to effectively make use of this. My initial thought is to implement JavaScript arrays. So, I have a select option available with values fetched from the database, and the select options are dynamic. By clicking on the "add row" ...

Utilizing a Static Image Path Prop in React JS: A Step-by-Step Guide

My Main Component import React from "react"; import TopModal from "./components/topModal"; // Passing productImage to the Child Component import productImage from "../../../../../../assets/images/juices.jpg"; import { makeS ...

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...

In JavaScript, the checkboxes in all columns of a table with over 200 rows can be set, but only the checkboxes in the rows

Seeking help to implement toggle buttons for checkboxes on a page with a large table fetched from an external system. The table can have over 200 rows or more. Currently, I am facing an issue where I can only access and manipulate the visible checkboxes o ...

Step-by-step guide on displaying SVG text on a DOM element using Angular 8

I have a FusionChart graph that I need to extract the image from and display it on the same HTML page when the user clicks on the "Get SVG String" button. I am able to retrieve the SVG text using this.chart.getSVGString() method, but I'm unsure of ho ...

How can I change a PHP for loop to Javascript?

Can the following code be converted to JavaScript? for (let lift of liftDetails) { document.write('<option>'+ lift["LiftMakes"] +'</option>'); } ...

Ordering v-data-table organizes checkboxes

Can someone explain why sorting this table causes some checkboxes to automatically be checked? And how is it possible for the checkboxes to be checked even when they are not in the "checked" array? <div id="app"> <v-app id="inspire"> ...

Trouble arises when managing click events within the Material UI Menu component

I've implemented the Menu Component from Material UI as shown below - <Menu open={open} id={id} onClose={handleClose} onClick={handleClick} anchorEl={anchorEl} transformOrigin={{ horizontal: transformOriginRight, vertical: t ...

React.js onClick does not display the dropdown

Hello, I have a question regarding my navbar icon functionality. When I click on the icon, it is supposed to open a dropdown menu. However, although the div name changes when clicked, the CSS properties remain the same as the initial class. I am unsure w ...

Iterate through a intricate array of JavaScript objects to extract their values

Looking for ways to extract total calorie and nutrition information from a large document displaying the nutritional data of a simulated recipe. Please review the codesandbox json file first. The objective is to capture the total calories and nutritive c ...

Having trouble getting Node.js moment timezone conversion to work properly?

Here's the plan for the code below: creating objects that expire at midnight in different timezones. To achieve this, I need to determine the user's location and corresponding timezone first. Then, take the current date in that timezone and forma ...

js problem with assigning the expression result of a regex operation

Let's talk about a JavaScript string scenario: "h" + "e" + "l" + "l" + "o" This particular string is extracted from a regex query, enclosed within [..], and here's how I'm isolating it: var txt = '"blahblahblah["h"+"e"+"l"+"l"+"o"]fo ...

The transition effects of Framer Motion do not seem to be working properly when switching between keyframe

Is there a way to create a smooth transition between two keyframe animation variants in CSS? Currently, when switching from one variant to another, the change happens instantly. How can I make it so that all properties transition smoothly? const variants = ...

Cleaning up HTML strings in Angular may strip off attribute formatting

I've been experimenting and creating a function to dynamically generate form fields. Initially, the Angular sanitizer was removing <input> tags, so I discovered a way to work around this by bypassing the sanitation process for the HTML code stri ...

Modifying the Carousel Interval on the Fly: A Guide

I've been trying to figure out how to adjust the interval time on a Bootstrap carousel. I know you can set it initially using: $('.carousel').carousel({interval: 1000 }); But what if I want the interval to change to 2 seconds after, let&ap ...