Utilizing the Power of GrapesJs in Vue3

Recently, I attempted to integrate the GrapesJS editor into my Vue.js project, but encountered some difficulties. The editor was not visible in the browser, and the designated tag for the editor appeared empty. Here is my editor configuration:

<template>
  <div ref="canvas"></div>
</template>

<script setup>
import grapesjs from "grapesjs";
import "grapesjs/dist/css/grapes.min.css";

const canvas = ref(null)
const editor = grapesjs.init(
  {
    container: canvas.value,
    fromElement: true, // Load existing HTML from the container
    storageManager: {
        type: "local", // Enable saving and loading from local storage
        autosave: true, // Enable autosave
        autoload: true, // Load previously saved data
    },
    canvas: {
        styles: [
            // Custom canvas styles
        ],
        scripts: [
            // custom scripts
        ],
    },
    plugins: ["gjs-preset-webpage"],
    pluginsOpts: {
        "gjs-preset-webpage": {
            // Options for the preset plugin
        },
    },
});
</script>

I experimented with this setup in another Vue 3 project (which uses the < script> syntax) and it functioned properly:

<template>
    <div ref="editor"></div>
</template>

<script>
import grapesjs from "grapesjs";
import "grapesjs/dist/css/grapes.min.css";

export default {
    name: app,
    data() {
        return {};
    },
    mounted() {
        const editor = grapesjs.init({
            container: this.$refs.editor,
            fromElement: true, // Load existing HTML from the container
            storageManager: {
                type: "local", // Enable saving and loading from local storage
                autosave: true, // Enable autosave
                autoload: true, // Load previously saved data
            },
            canvas: {
                styles: [
                    // Custom canvas styles
                ],
                scripts: [
                    // custom scripts
                ],
            },
            plugins: ["gjs-preset-webpage"],
          pluginsOpts: {
                "gjs-preset-webpage": {
                    // Options for the preset plugin
                },
            },
        });
    },
};
</script>

In my current project, I also tested the < script> version which worked fine. I suspect the issue may be related to the < script setup> syntax.

If anyone can offer insight into why the editor is not loading in the first case and suggest a solution, I would greatly appreciate it.

Answer №1

After hours of troubleshooting, I finally managed to fix the issue by adding the onMounted hook. It's a mystery why it didn't work before despite my multiple attempts. I was confused and frustrated for an entire day until it suddenly started working.

I have decided to keep this post here in case someone else encounters the same problem. Below is the updated code snippet:

<template>
  <div ref="canvas"></div>
</template>

<script setup>
import grapesjs from 'grapesjs';
import 'grapesjs/dist/css/grapes.min.css';

const canvas = ref(null);
let editor
onMounted(() => {
   editor = grapesjs.init({
    container: canvas.value,
    fromElement: true,
    storageManager: {
      type: 'local',
      autosave: true,
      autoload: true,
    },
    canvas: {
      styles: [],
      scripts: [],
    },
    plugins: ['gjs-preset-webpage'],
    pluginsOpts: {
      'gjs-preset-webpage': {},
    },
  });
});
</script>

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

Module request: How can I save the gathered cookies as a variable?

library: https://www.npmjs.com/package/request I am attempting to simultaneously log in with multiple accounts on a website. To manage each session effectively, I plan to create an object where I will store the cookies associated with each account. Now, ...

stuck with an outdated dependency causing issues with create-react-app

Encountering a problem with create-react-app failing due to react-scripts expecting an older version of a dependency, making it difficult to select the new version as suggested. This appears to be an interface issue. Interestingly, I can successfully inst ...

When the browser is not in the foreground, clicking on the Bootstrap datepicker with Selenium does not register

When you click on the input field <input id="dp1" class="span2" type="text" value="02-16-2012"> If the browser is in the background, the datepicker popup will not display. Even using javascript or jquery to click the input field does not show the ...

Unit testing controllers in AngularJS with Karma often involves setting up mock services to simulate dependencies

Currently, I am immersed in the development of a Single Page Application using AngularJS as part of my Treehouse Full Stack JavaScript TechDegree. My main focus right now is on conducting unit tests for the controllers. The challenge lies in testing contro ...

Does Virtual DOM speed up or slow down applications?

After reading through the Svelte JS documentation, I noticed that one of its advantages is the absence of a Virtual DOM, making apps built with this framework faster and lighter. However, conflicting information suggests that having a Virtual DOM can act ...

Challenges with jQuery: Appending strings to a dynamically selected element

Hello everyone, I have a question regarding adding the string 'url(" ")' around my Any assistance you can provide would be greatly appreciated. Thank you! $(function() { $('#list li a').hover( function(){ $("#meow").css( " ...

Opt for utilizing v-model over the name attribute when implementing Vee-Validate

Recently, I've embarked on a journey to learn how to create Single Page Applications using Vue. Today, my focus is on Vee-Validate. When working with Vee-Validate, the validation requires the name attribute to be filled in. Otherwise, a warning messa ...

JavaScript communication between clients and servers

I am looking to develop two scripts, one for the client-side and one for the server-side. I came across a snippet that allows for asynchronous calling of JavaScript: <html> <head> </head> <body> <script> (function() { ...

Is Vue capable of recording and tracking all user interactions - perhaps for testing purposes?

Over the past few months, I have been working on developing a Vue one-page application. We are nearing the end of the alpha version and will soon deliver it to our clients for real live testing. However, our end-users are regular office workers with no pro ...

Retrieve the information sent back by AngularJS and pass it to a JavaScript function

I am working on a form using AngularJS to create a new object, which is returned as "marker." $scope.createMarker = function() { $http.post('/markers/create', $scope.marker) .success(function(data) { }) .error(funct ...

What are some effective ways to test asynchronous functions in React?

Looking for help to test async/Promise based methods in React components. Here is a simple example of a React component with async methods: import server from './server'; class Button extends Component { async handleClick() { if (await ca ...

Stellar for occasions that don't come around often

Is it worth utilizing a Comet for events that do not require real-time updates, but can have a delay of around 1 minute? Examples could include: updates on Twitter statuses notifications on Facebook While Comet is commonly used in chat applications (suc ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

What is the best way to conditionally render one of several components in a manner that is compatible with React's change detector?

Within my CRUD application, I have incorporated various reusable components such as a "generic" DialogComponent, along with several non-reusable components. Throughout the development process, I have encountered numerous instances where I need to either: ...

Retrieve the data from an HTTP Request using AngularJS

I've been working on creating a JavaScript function that sends an HTTP Request to retrieve data, but I'm struggling with how to handle and use the result in another function. Here are the two functions I've tried (both intended to achieve t ...

Guide on testing a function with a dependency in Angular through unit testing

Attempting to dive into unit testing, I have grasped some of the basics. However, my current challenge lies in testing a method within my code. This particular method involves calling a function from oidc-client.js that handles user sign-ins. My spec fi ...

Refreshing image does not reload

function updateimage(){ $("#fileimg").attr("src","path/to/image.jpg"); $('#fileimg').fadeIn('slow'); setTimeout(updateimage, 5000); } Greetings, I am trying to refresh an image every 5 seconds but it's not working as ...

Issue uploading with Candy Machine Version 2/ complications with directory

For some reason, I am encountering issues with the upload operation. Switching from relative to absolute paths did not resolve the error, and using the -c flag for the directory containing images and JSON files is causing a problem. However, other flags ...

The Lerna command for adding packages fails with an error message stating that the packages are not related

Currently, I am utilizing lerna to manage a multirepo containing interrelated packages. This issue only arose after installing a new operating system. Whenever I attempt to utilize lerna add to add a dependency from one package to another, an error occurs ...

Tips on utilizing jQuery or JavaScript to efficiently filter out outcomes exceeding a specified range

<input type="range" name="rangeInput" min="100000" max="750000" onchange="updateTextInput(this.value);"> Displayed above is the slider code that provides a value output below. <div id="sliderValue"> <p>Max Value £</p> <input t ...