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:
- Is my method of making this modular correct?
- How can I retrieve the value of
exportUrl
in myindex.vue
file?
If you can provide any assistance or guidance, it would be highly appreciated. Thank you in advance!