The integration of VueJS with the Canva Button JS API amplifies the

I have been exploring Canva's Button JS API which can be found at

My goal is to implement a modular approach in utilizing their API, only loading the CanvaJS when necessary. My implementation involves triggering the load function when a button is clicked, as shown below.

Below is an excerpt from my vue file named index.vue:

import CanvaService from '@app/services/canva';
...

<button class="btn btn-primary" @click.prevent="drawCanva()">Click Here!</button>
...
methods : {
 drawCanva() {
   CanvaService.load();
 },
}

The code snippet provided showcases my canva.js or CanvaService script:

class CanvaService {

    constructor (config) {
        this.api_key = "XXXXX XXXX";
        this.api = "";
        this.has_init = false;
    }

    load() {
        let _this = this;
        if(!_this.has_init) {
            (function (document, url) {
                var script = document.createElement('script');
                script.src = url;
                script.onload = function () {
                    _this.init();
                };
                document.body.appendChild(script);
            })(document, 'https://sdk.canva.com/v2/beta/api.js');
        } else {
            _this.createDesign();
        }


    }

    init() {
        let _this = this;
        (async function () {
            if (window.CanvaButton) {
                if (!_this.has_init) {
                    _this.api = await window.CanvaButton.initialize({
                        apiKey: _this.api_key
                    });

                    _this.has_init = true;
                    _this.createDesign();
                } else {
                    _this.createDesign();
                }
            }
        })();
    }

    createDesign() {
        this.api.createDesign({
            type: 'Poster',
            onDesignOpen: ({ designId }) => {
                // Triggered when editor finishes loading and opens a new design.
                // You can save designId for future use.
            },
            onDesignPublish: ({ exportUrl, designId }) => {
                console.log("onDesignPublish");
                console.log(exportUrl);
                return exportUrl;
            }
        });
    }
}

export default new CanvaService ();

Although not well-versed in Javascript, I seek validation on whether my modular approach is appropriate. Two specific questions I have are:

  1. Is my method of making this modular correct?
  2. How can I retrieve the value of exportUrl in my index.vue file?

If you can provide any assistance or guidance, it would be highly appreciated. Thank you in advance!

Answer №1

1 - Transforming your Service class into a mixin will allow you to access the correct "this" when invoking your methods :)

Mixin documentation: https://v2.vuejs.org/v2/guide/mixins.html

2 - By utilizing a mixin, you can store your URL within the data of the Vue component.

createDesign() {
    this.api.createDesign({
        type: 'Poster',
        onDesignOpen: ({ designId }) => {
            // Triggered when editor finishes loading and opens a new design.
            // You can save designId for future use.
        },
        onDesignPublish: ({ exportUrl, designId }) => {
            console.log("onDesignPublish");
            console.log(exportUrl);
            this.myExportedURL = exportUrl;
        }
    });
}

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

Retrieve Django imagefield file name using jQuery before submitting

Exploring the essential Django image file upload procedure, where the image model incorporates the ImageField class. There's a custom display button replacing the default upload button which usually showcases the image name alongside it. Hence, the ne ...

Sending a JSON Object to an API endpoint using the $.ajax method

While attempting to extract data from a form by clicking a button and sending it to a web method in my code behind, I am aiming to pass it as a JSON object, following what seems to be the convention. Below is the current code snippet that I have, but unfor ...

Place an image at the center with a height set to 100% within a div that has a fixed height and

Apologies for asking about this topic again, but I have been unable to find a solution where the image fills 100% of the height. If you'd like to see the issue in action, here's a link to the jsfiddle: http://jsfiddle.net/BBQvd/3/ I'm just ...

Error message: When initiating AJAX requests in ASP.NET, the function is not defined for undefined

I recently followed a tutorial on creating AJAX requests for CRUD operations in an AngularJS application. However, upon trying to perform an AJAX request to retrieve data from the database, I encountered the following error when launching my application: ...

Scraping a JavaScript page using Python without requiring a browser installation

Currently, I am facing a challenge in scraping an HTML element from a webpage. The content within this element is dynamically generated by Javascript, making it impossible to retrieve using a simple requests.GET: response = requests.get(url). While explor ...

"Is there a way to extract a value from a JSON object using

I have an object with the following key-value pairs: { 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812', 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1&a ...

The URL routing in Vue-router seems to be incorrect as it directs to the wrong page. To fix this issue, make sure to include a '#' before the

Welcome to my website! Check out my home page here: https://i.sstatic.net/znfq0.jpg If you're interested in reading my blog, visit the blog page here: https://i.sstatic.net/oiYSY.png I've built this site using vue3. Here's a snippet of th ...

When you click, apply the hidden class to all the div elements

Is there a way to apply the .hide class to all .slide divs whenever the .option button is clicked? If so, how can I modify my JavaScript code so that all .slide divs receive the .hide class (if they don't already have it) upon clicking the .option bu ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

Express.js POST Request Not Being Accepted | 404 Error Detected

I am encountering difficulties implementing PayPal on my website. Whenever I attempt a post request, including using Postman, I receive a standard 404 error page instead of the expected response. The console shows no errors, leading me to believe that the ...

Tips for designing a versatile component to handle numerous buttons triggering form pop-ups

library used: mui 5.4.1 To implement a TableCell with an IconButton that triggers the opening of a Form, follow this code snippet. const items = [ { id: "001", name: "A", price: 2000 }, { id: "002", name: &q ...

Verifying the authenticity of a Stripe discount code

My goal is to allow users to apply a coupon code on my website, triggering a check in the Stripe dashboard. Currently, I have implemented the following code snippet, but I am facing an issue with transferring the validCoupon data from the client side to th ...

Creating a dynamic dropdown menu based on a class value using JavaScript in PHP

There are two dropdown menus on my webpage that display information from my SQL table. The first dropdown contains different "Colors," and the second dropdown contains members associated with each color group. Each member is categorized into different optg ...

What is the best way to load a partial in Rails asynchronously with AJAX?

I am currently using the following code to load a partial when I reach the bottom of a div containing a table: $(document).ready(function () { $("#pastGigs").scroll(function () { if (isScrollBottom()) { $('#pastGig ...

Issue with Web Worker functionality in SvelteKit on Firefox version 106.0.5

I've set up a function in my main file like this: const loadWorker = async () => { const SyncWorker = await import("$lib/canvas.worker?worker"); syncWorker = new SyncWorker.default(); syncWorker?.postMessage({}); ...

Utilizing AngualarJS to bind data to intricate objects using the $resource functionality

Currently, I am working on a restful service that retrieves an order along with a list of items. In my project, I am developing a screen where users can edit specific items within the order. To achieve this, I need to display the list of items before locat ...

Add the Selected Value to the Title

Is there a way to dynamically add the selected value from each select element to its corresponding heading without requiring user interaction? I need this to happen as soon as the page loads. Here is an example in a jsfiddle https://jsfiddle.net/dqfvyvdt/2 ...

The dimensions of the sprites within Three.js geometry

I am interested in creating an animation of sprites moving along a figure, particularly sprites that walk along the figure. An example of what I envision can be seen here: http://armsglobe.chromeexperiments.com/ I found some helpful information related t ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...