Mapping DOM elements to VueJS components for hydration is a key process in facilitating

I have a specific requirement and I am exploring potential solutions using VueJS, as it offers the convenient feature of hydrating pre-rendered HTML from the server.

In my Vue components, I do not define a template within the .vue file, but I need them to attach (hydrate) to DOM elements seamlessly. My only concern is how to attach child components in this context.

Could you provide an example?

<div class="page-component">
 <h1 v-text="pageTitle">Page Title</h1>

 <div class="child-component">
  <h2 v-text="childTitle">Child Title</h2>
 </div>
</div>

I have two components: PageComponent, responsible for handling the v-text in the h1 element within the root DOM element with the class .page-component, and ChildComponent, which should attach to the DOM element with the class .child-component and deal with the v-text in the h2 element.

Currently, I am struggling to understand how to achieve this without explicitly defining a matching template in the .vue file. While I see that server-side rendering (SSR) with the vue SSR render package handles this correctly, I am looking for a way to create templateless components that utilize the rendered content from any server (note: I use a Java server and cannot rely on the npm SSR package). Additionally, I want to ensure that these components are attached correctly to their respective sections within the complete HTML document.

I attempted a solution where I instantiated a PageComponent and mounted it like this: new PageComponent().$mount('.page-component'). However, this approach led to issues when trying to interpolate Vue-related attributes, such as the v-text directives, resulting in conflicts with the ChildComponent's properties.

In conclusion, I am seeking a method to instruct the PageComponent to delegate interpolation control to a child component at a specific point in the DOM subtree, rather than attempting to handle interpolation independently.

I trust that my scenario is now clearer.

Answer №1

If my understanding is correct, you aim to deliver an HTML page from your Java server (without using Vue SSR) and then "hydrate" it on the client side with Vue components without duplicating the HTML structure in the component templates (referred to as "templateless").

Additionally, you want dynamic data to be sourced from each component without explicitly defining everything in the top-level component (expecting it to pass control for interpolation to a child component).

However, according to Vue's Component Slots documentation linked here, compilation (interpolation) occurs where the components are used:

Everything in the parent template is compiled in the parent scope; everything in the child template is compiled in the child scope.

In your code example, this means that Vue requires both `pageTitle` and `childTitle` variables to be defined within your "page-component" Component (as data, props, computed properties, etc.)

Unless Scoped Slots are utilized, which have a specific syntax like shown below:

Vue.component('my-child-component', {
  template: '<div><slot :childTitle="myChildTitle"></slot></div>',
  data() {
    return {
      myChildTitle: 'Child Title from my-child-component',
    };
  },
});

function activateVue() {
  new Vue({
    el: '#app',
    data: {
      pageTitle: 'Page Title from page-component',
    },
  });
}
<button onclick="if (typeof Vue === 'undefined') {alert('Vue is not loaded yet');} else {activateVue();}">Activate Vue</button>

<div class="page-component" id="app">
  <h1 v-text="pageTitle">Page Title from server</h1>

  <div class="child-component" is="my-child-component">
    <div slot-scope="{childTitle}">
      <h2 v-text="childTitle">Child Title from server</h2>
    </div>
  </div>
</div>

<script src="https://unpkg.com/vue@^2.5"></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

React does not allow _id to be used as a unique key

When I retrieve the categories from my allProducts array fetched from the database using redux-toolkit, I filter and then slice the array for pagination before mapping over it. However, I keep encountering a warning: Each child in a list should have a un ...

utilizing ng-option to present choices in a dropdown menu

I have been implementing a scroll-down menu in my application using options. However, I now want to switch to using ng-option to populate the values from a JavaScript file. I also require assistance with writing AngularJS code for this task. Below is a s ...

Exploring the Capabilities of Drag-and-Drop Functionality in jsTree and DataTables

Is it possible to copy nodes from a jsTree that I've dragged to a cell in a DataTable? I'm struggling with getting this functionality to work. Any suggestions on how to achieve this? I am not seeing any alerts appear. This is the HTML code: &l ...

How come the Qunit counter doesn't seem to ever reach its expected target value during this test?

I'm currently stuck on a Qunit test related to jQuery Mobile's listview.filter extension. I can't figure out how the variable _refreshCornersCount ends up with a value of 3. Below is the section causing confusion. module( "Custom search ...

I am not sure how to properly execute this asynchronously

I have compiled a comprehensive list of everything related to this command I've been developing, and here is the error it keeps throwing at me. I tried testing if the image search feature was working properly, but instead, here's what I got: Synt ...

Vue.js - issue with filtering results not displaying correctly

I am currently working on an app that displays items from an external JSON file and I'm looking to implement a search input feature for filtering. Initially, the app was displaying items properly. However, once I added the filter function, it stopped ...

Attempting to coordinate a virtual meeting through the utilization of the Zoom API

I'm currently in the process of developing a website using Node.js, Express.js, and Mongodb. One feature I am working on is the ability for users to schedule Zoom meetings directly within the website. The desired functionality would be for users to sc ...

Input field in a tableview

I have a ListView that features a dropdown, 4 textboxes and buttons. My goal is to only show the fourth textbox (enclosed in a span) when the dropdown value in each row of the ListView is set to 2. For instance, if there are 5 records being displayed in t ...

The response from getStaticProps in Next.js is not valid

While following the Next.js documentation, I attempted to retrieve data from a local server but encountered an error message: FetchError: invalid json response body at http://localhost:3000/agency/all reason: Unexpected token < in JSON at position 0 ...

Interactive game created using JavaScript input

I've scoured the internet for guidance on creating a text-based game that utilizes user input, but all I come across are tutorials focusing on button interactions. What I envision is triggering different responses based on specific user inputs. For i ...

One can only iterate through the type 'HTMLCollection' by utilizing the '--downlevelIteration' flag or setting a '--target' of 'es2015' or above

I'm currently working on developing a loader for my static grid. I've incorporated the react-shimmer-skeleton package source code, but I'm encountering issues with eslint in strict mode. You can find the respective repository file by followi ...

Using the Vue Class Component syntax in conjunction with TypeScript

I found an example on https://github.com/vuejs/vue-class-component that uses the new component syntax in vuejs3, but I'm trying to use TypeScript directly instead of babel. Here is what I attempted: <script lang="ts"> import Vue from "vue" impo ...

What causes my backend to crash when incorrect credentials are entered?

Whenever I input incorrect credentials on my login page, it causes the backend to crash. I want to avoid this situation and prevent my backend from crashing. Can somebody please assist me in identifying and rectifying the mistake? I am using MongoDb as my ...

Storing JSON data using Vuex

As I am delving into the world of Vuex store used with vue.js, I find myself wanting to implement it in a specific scenario. 1. Is STATE referring to any data, whether static or dynamic, that is provided by the server or stored in a JSON format? TEMPLATE ...

Toggle display of divID using Javascript - Conceal when new heading is unveiled

At the moment, I have implemented a feature where clicking on a title reveals its corresponding information. If another title is clicked, it opens either above or below the previously opened title. And if a title is clicked again, it becomes hidden. But ...

What could be causing the issue with the Vue CLI not working after installation via npm 6.9.0?

Whenever I try to run the command below: vue create hello-world I receive this message : 'vue' is not recognized as an internal or external command, operable program or batch file. It's been a month and I'm still struggling to fin ...

Guide to ensuring every request in an Express.js application contains a cookie

Currently, I am in the process of developing a CRUD application using both React and Node. As part of my development, it is crucial for me to validate whether the cookie is present or not for each request. app.all("*", (req,res) => { // If the cookie ...

How to modify the output value in Vue.js when the input is blank?

As a newbie to vue.js, I am looking to update the displayed text to match the placeholder string if the input value is empty. Below is the code snippet I have in mind: <div id="form"> <input class="input-f" type="text" placeholder="please enter y ...

Creating a form submission event through Asp.net code behind

Is there a way to change the onsubmit parameter of a form in an asp.net project, specifically from the master page code behind of a child page? I am interested in updating the form value so that it looks like this: <form id="form1" runat="server" onsu ...

Incorporate a generic type into a React Functional Component

I have developed the following component: import { FC } from "react"; export interface Option<T> { value: T; label: string; } interface TestComponentProps { name: string; options: Option<string>[]; value: string; onChang ...