Is it possible for me to create a nested component without having to make a new file

What I desire:

Home.vue

<template>
    <div>
        <p>{{message}}</p>
        <ChildComponent/>
    </div>
</template>

<script setup>
import { ref, defineComponent } from 'vue';

let message = ref('Hello World!');

let ChildComponent = defineComponent({
    name: 'ChildComponent',
    template: `<p>{{subMessage}}</p>`,
    setup() {
        let subMessage = ref('This is a sub-message');

        return { subMessage };
    }
});
</script>

I had the idea of creating a small dedicated component for one page.

The structure looks good. But unfortunately, it's not functioning as intended.

I aim to avoid creating a new file and using export default.

Additionally, I prefer not to register it globally.

Is there any solution to create a component in this manner?

=====

solution:

app.js

import { createApp } from 'vue'; (X)

import { createApp } from 'vue/dist/vue.esm-bundler.js'; (O)

Success! Why...

Answer №1

The reason your code is not working is because the template of the Child component is provided as a string.

Note on In-Browser Template Compilation

When using Vue without a build step, component templates are written either directly in the page's HTML or as inlined JavaScript strings. In such cases, Vue needs to ship the template compiler to the browser in order to perform on-the-fly template compilation. On the other hand, the compiler would be unnecessary if we pre-compile the templates with a build step.

Our default tooling setups use the runtime-only build since all templates in SFCs are pre-compiled. If, for some reason, you need in-browser template compilation even with a build step, you can do so by configuring the build tool to alias vue to vue/dist/vue.esm-bundler.js instead

You are utilizing Vue Single File Components (SFC) - which implies you are using Vite or Vue CLI. Both are set up to employ a runtime-only build and precompile all Vue templates within the <template> tags of all SFC files. However, your Child component has a template as a string, requiring the build to include the compiler. This is why importing from vue/dist/vue.esm-bundler.js resolves the issue (although it is recommended to follow the documentation instead of importing like that to avoid potential version conflicts leading to difficult debugging).

An alternative solution is to steer clear of string templates and create your simple component using render function

<script setup>
import { ref, defineComponent, h } from 'vue'

const Child = defineComponent({
    name: 'Child',
    setup() {
        const bar = ref('bar');
        return () => h('span', bar.value)
    }
});
</script>
    
<template>
  <Child></Child>
</template>

Demo

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

Is the process.env variable used universally for environmental variables, or is it specifically designed for use in Node.js

Can process.env function as a universal environment variable or is it exclusive to NodeJs? https://nodejs.org/dist/latest-v8.x/docs/api/process.html#process_process_env Instructions on setting it using the node command are provided: $ node -e 'proc ...

Close overlay panel in PrimeFaces calendar

One of the components I’m currently working with is an overlayPanel that contains a calendar. Here's a snippet of the code: <p:overlayPanel hideEffect="fade" showCloseIcon="true" dismissable="true" > <h:form> <p:p ...

It appears that Nodemon has stopped functioning correctly. To use Nodemon, simply input the following command: nodemon [nodemon options]

nodemon has always been reliable for me. I used to run nodemon server and it would automatically watch for updates and restart the server file. However, lately when I try to do this on my Windows cmd, I get the following message: Usage: nodemon [nodemon o ...

Retrieve the texture's color based on the UV coordinates

Currently, I'm working with version 73 of V. I am dealing with UV coordinates obtained from the intersection of a raycaster and a texture of an object. Is there a way to extract the color (RGB or RGBA) of the used texture at these specific UV coordina ...

Problem with Angular 2 Typings Paths in Typescript

Currently, I am in the process of learning how to create a Gulp build process with Angular 2 and Typescript. Following the Quick Start guide has allowed me to get everything up and running smoothly. However, I have decided to experiment with different fold ...

Leveraging highland.js for sequentially executing asynchronous functions while maintaining references to the initial stream data

I am dealing with a series of events: var eventStream = _([{ id: 1, foo: 'bar' }, { id: 2, foo: 'baz' }]); My task is to load an instance of a model for each event in the stream (my Data Access Layer returns promises) and then tri ...

Challenges regarding placement and z-index are causing issues

Currently, I am attempting to make the menu overlap the content on my webpage. However, I am facing an issue where it moves the content box instead of overlapping it. I have already experimented with the position: relative concept, but unfortunately, the ...

Listening to React events on multiple elements in an array

When my React render function is running, it ends up rendering a group of elements: data.map((element) => { return <Object onChange={this.onObjectChange} />; }); I'm wondering, what is the best approach to determine which specific object ...

How can I connect the Bootstrap-datepicker element with the ng-model in AngularJS?

Below is the html code for the date field : <div class='form-group'> <label>Check out</label> <input type='text' ng-model='checkOut' class='form-control' data-date-format="yyyy-mm-dd" plac ...

Transferring elements from one array to multiple arrays

I have been working with the basics of JavaScript arrays and here is my code snippet: let arr = ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B&apos ...

The custom component I created seems to be unaffected by the inline styles in React

Having an issue with a custom component where I am trying to add margin-top in one of my uses. I attempted using <MyComponent style={{ marginTop: '10px' }}> and also const myStyle = { marginTop: '10px' }; `<MyComponent style= ...

Prevent input from being cleared when selecting an option with React-Select

Unfortunately, there was no satisfactory solution to this question so I will provide an answer: The issue arises when trying to utilize React-Select with a persistent input value that remains even after selection or blurring. Regrettably, this functionali ...

Setting a proper prop path for nested data within a table component in Element UI using Vue JS

I'm currently facing an issue with form validation in a table layout using element-ui. Specifically, I am struggling to pass a valid prop to the el-form-item component. The structure of my data model is as follows: form: { invoices: [ { ...

Having trouble displaying the selected button in React

Is it possible to include multiple functions within an onclick event? Check out the code snippet below: import React from 'react'; class Counter extends React.Component { state = { count: 0, inc: 'Increment', ...

Script for migrating MongoDB attributes to an array

I am in the process of creating a database migration, and the current structure is as follows: { "site" : { "name" : "siteName1" }, "subStages" : [ "subStage1", "s ...

Is there a way to prevent a 'keyup' event from being triggered by a 'keydown' event?

I have a tool that resolves zip codes and I am currently utilizing a keyup event handler to trigger a server query once the input length reaches 5 characters. However, I want to prevent unnecessary calls to the script, so I am exploring the possibility o ...

Is it possible to design a Typescript type that only contains one property from a defined set and is indexable by that set as well?

I have the different types listed below: type OrBranch = { or: Branch[] } type AndBranch = { and: Branch[] } I need a type called Branch that can either be an OrBranch or an AndBranch. I initially attempted this: type Branch = AndBrand | OrBranch ...

It is not possible to make a call to Response.Redirect from within a static method

Hello, I am attempting to execute a webmethod using ajax from an aspx page. Essentially, I would like to redirect to another aspx page with a query string, but I need to do it through <a href> because it is part of a jQuery menu. Based on my underst ...

Changes in a deep copy of an object in a child component are directly reflected in the parent object in VueJS

Let's begin by discussing the layout. I have a page dedicated to showcasing information about a specific company, with a component Classification.vue. This component displays categories of labels and the actual labels assigned to the current company. ...

The function 'toBlob' on 'HTMLCanvasElement' cannot be executed in react-image-crop because tainted canvases are not allowed to be exported

Currently, I am utilizing the react-image-crop npm package for image cropping purposes. Everything works perfectly when I pass a local image as props to the module. However, an issue arises when I try to pass a URL of an image fetched from the backend - th ...