Perform a prerender of a Vue.js 2.0 component (resembling the functionality of this.$compile in Vue 1)

I'm currently working on developing reusable components specifically for gridstack.

One issue I've encountered is the absence of a simple equivalent to the this.$compile method from vue 1. I came across this example that caught my attention.

Here's the vue script I'm using:

export default {
  components: {
    'horizontal-fab': HorizontalFab,
    'd-widget': DWidget
  },
  data () {
    return {
  }
},
mounted () {
  var options = {
    cellHeight: 80,
    verticalMargin: 10,
    width: 3
  }
  $('#grid-stack').gridstack(options)
},

addWid () {
  var grid = $('#grid-stack').data('gridstack')
  grid.addWidget('<d-widget></d-widget>', 0, 0, 1, 1, true)
},

addGraph () {
  var grid = $('#grid-stack').data('gridstack')
  grid.addWidget(`
    <div class="grid-stack-item" data-gs-width="4">
      <div class="grid-stack-item-content">
        <p>HTML (added)</p>
      </div>
    </div>
  `, 0, 0, 1, 1, true)
}

Below is the relevant html code:

<span @click="addGraph" >Line graph</span></li>
<span @click="addWid">Sparklines</span></li>
...
<div id="grid-stack" class="grid-stack grid-stack-3">
  <d-widget data-gs-x="0" data-gs-y="0" data-gs-width="1" data-gs-height="1"></d-widget>
</div>

The core problem at hand:

The addGraph method functions flawlessly, while addWid encounters issues. Strangely enough, when directly inserted as a component in the HTML, it works fine.

My assumption is that the HTML content from the component isn't being precompiled. In vue1, this was resolved using compile.

Various attempts have been made:

  1. Mount, recommended here, but due to not recognizing defined components, it didn't work.
  2. I stumbled upon suggestions to make it work with push, as seen here. However, my familiarity with vue is limited and implementing this approach poses challenges, especially considering different block types needing to be treated uniformly by gridstack. Additionally, the same component may appear multiple times within a board with varying parameters.
  3. A method to compile a standalone component has surfaced, mentioned here, yet it seems to be discouraged, hence seeking alternatives.
  4. References to render functions were observed, unfortunately, my expertise level isn't sufficient to put them into practice.

To conclude, any insights or guidance on these methods, or perhaps suggestions for alternative implementations would be highly valued. It's crucial to consider the functionality of the gridstack script rather than simply inserting elements.

Thank you!

UPD: definition of d-widget:

This essentially represents a single component, delineated in a separate file labeled Widget.vue

<template>
<div class="grid-stack-item" data-gs-width="4">
    <div class="grid-stack-item-content">
        <p>Wiiidget! (added)</p>
    </div>
</div>
</template>
<script>
export default {
  data () {
    return {
    }
  }
}
</script>

Answer №1

If you utilize the mount method, you can retrieve the necessary information to pass to grid.addWidget.

The first step is to transform the component into a constructible entity.

const MyWidget = Vue.extend(DWidget);

Subsequently, we can instantiate that constructor.

const mounted = new MyWidget().$mount();

By passing nothing to $mount(), the component will not be added to the DOM. The element it created can be accessed using mounted.$el. It is expected that this element can be passed to addWidget.

grid.addWidget(mounted.$el, 0, 0, 1, 1, true);

Answer №2

Upon the recommendation of @Bert, I utilized the mount method as suggested. Surprisingly, his approach worked flawlessly. Below is an implementation of the addWid() method, designed to function as a reusable component:

addWid () {
  const MyWidget = Vue.extend(DWidget)
  const mounted = new MyWidget().$mount()
  var grid = $('#grid-stack').data('gridstack')
  grid.addWidget(mounted.$el, 0, 0, 1, 1, true)
}

This solution may prove beneficial to others in similar scenarios!

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

Encountering an error "[$rootScope:inprog]" while using Angular select with ngModel

I'm still learning my way around Angular, but I have a basic understanding. Right now, I'm working on assigning access points to a building using a <select> element. I've created a simple controller for this task, but it's not fun ...

Utilizing a single delete function for a post request in jQuery or a PHP request

Seeking guidance on how to achieve a specific task. I have a controller that loads a view containing a table listing pages from my database. Each row in the table has an icon that, when clicked, performs one of two actions. If the user does not have javas ...

Stripping away HTML tags from a JSON output

I'm attempting to retrieve a JSON result using jQuery. $.ajax({ type: "GET", url: "http://localhost:8080/App/QueryString.jsp?Query="+query, contentType:"text/html; charset=utf-8", dataType: "json", success: function(json) { if(data!="") ...

Save room for text that shows up on its own

I am currently dealing with a situation where text appears conditionally and when it does, it causes the rest of the page to be pushed down. Does anyone know the best way to reserve the space for this text even when it's not visible so that I can pre ...

Is there a way to preserve EXIF data when converting an image to base64?

I am currently facing an issue with reading a local image that has been created with a different exif.Orientation based on the degree of rotation. const exifData = piexif.load(data.toString("binary")); // Assign the desired orientation value ...

The scrolling action triggered by el.scrollIntoViewIfNeeded() goes way past the top boundary

el.scrollIntoViewIfNeeded() function is used to scroll to element el if it's not within the visible browser area. Although it generally works well, I have encountered some issues when trying to use it with a fixed header. I have provided an example s ...

Leverage cookies within a custom service in AngularJS

I attempted to implement angular cookies within a custom service, only to encounter the following error: Unknown provider: ngCookiesProvider <- ngCookies <- checkLoginService My approach involves storing modules, controllers, and services in separat ...

What is the best way to resume a paused animation using JavaScript?

My first game involves triggering an animation that transitions the game screen to greyscale when the character dies. Despite my efforts, I have been unable to successfully trigger this animation using document.getElementById("object").animationP ...

JavaScript: Discovering similar property values within complexly nested arrays and objects

I am facing an issue with matching values from two JSON sources. While using the javascript find method, I have found that it works when the nesting of the "cities" array is one level more shallow (just an array of objects), but doesn't work with deep ...

A Guide to Setting the HTML Lang Attribute on a Specific Page in Next.js

I have a website built with Next.js that consists of several pages. Most of the pages are in English, but there is one page that is in French and does not have an English version. How can I assign the lang attribute to the HTML tag for this specific page ...

Exploring the Integration of Material UI DatePicker with Firestore in ReactJS: Converting Firestore Timestamps to Date Format

The database is correctly recording the date, however, when displayed, the DatePicker does not recognize the date from the database as it is in timestamp format (seconds and nanoseconds). <DatePicker margin="normal" label="Data do pedido" ...

Updating JSON objects in jQuery with string keys

I have an array variable containing JSON data and I need to update specific values within the array using string keys. Here is a snippet of what my array looks like: { "all": [ { "image":{ "URL":"img/img1.jpeg", ...

Using the data () method to define Chart.js annotations in Vue.js can cause them to malfunction

I've encountered an issue while incorporating chartjs-plugin-annotations into a Vue.js application We have successfully integrated ChartJS charts into our Vue applications by defining the chart's config within the data () section of the componen ...

Achieving dynamic HTML element addition through JavaScript while maintaining their record in PHP

There is an input box where the user specifies the number of new DIV elements to be added dynamically. This request is then sent to PHP via Ajax, where it prepares an HTML DIV with some inner input tags. Each DIV has a unique id attribute generated increme ...

Retrieve the difference in time from the current moment using moment.js

I am trying to implement a functionality where I can track when my data was last updated. - After hitting the 'Update' button, it should display 'Update now' - If it has been n minutes since the update, it should show 'n mins ago& ...

What is the best way to set a default value for a specified Date format retrieved from an API?

Here are examples of different data formats for ReleaseDate: 2014-09-23 09:00:00.923Z /Date(1407369600210)/ If you want to access this information from an API, you can use the following object dot-notation: result.data.Items[0].ReleaseDate Sometimes, ...

Listening to messages in a Vue.js template

Here is the template named "template-main": ... <template> ... <slot></slot> ... </template> ... Next, there is a simple page that utilizes this template: <template> <template-main> . ...

Using jQuery to incorporate a variable into JSON schema markup

For my current project, I am attempting to extract the meta description and incorporate it into JSON schema markup. However, I am facing difficulty in passing the variable properly into the JSON structure. My initial approach was as follows: <script&g ...

Using a jQuery prompt to ensure data is saved when leaving the page

Is there a way to prompt users to save data on specific pages before they leave them? I'm thinking of using the jQuery UI dialog box. I understand that I can utilize the onbeforeunload event to recognize when a user is about to leave the current page, ...

The onchange tag fails to trigger my Javascript function when selected

Here is the code I have: JS: function updateLink() { var selType = document.getElementByID("Types"); var selLen = document.getElementByID("Length"); var selLoc = document.getElementByID ...