Need to import Vue component TWICE

My question is simple: why do I need to import the components twice in the code below for it to function properly?

In my current restricted environment, I am unable to utilize Webpack, .vue Single File Components, or npm. Despite these limitations, I managed to piece together a functioning Vue app using TypeScript files. However, I am puzzled by the necessity of importing the component file and then requiring it as a component.

This setup may not be ideal, especially since we plan to deploy this as a Proof of Concept with developers who are also new to Vue. Therefore, I would like to improve this process and avoid introducing bad practices from the beginning.

index.ts

import * as Vue from "vue";
import * as Apple from "./App";                 
Vue.component('apple2', Apple.default);          

let v = new Vue({
el: "#app",
components: { Apple},                           
template: `
<div>
    <apple2/>                                   
</div>`,
data: {
    name: "World"
},

});

App.ts

import * as  Vue from "vue";
import * as fred from  "./Hello";                   
Vue.component('fred2', fred.default);                

export default Vue.extend({
name: 'Apple',
template: `
<div>
    <fred2 :name="name" :initialEnthusiasm="4"/>     
</div>`,
data() {
    return { name: "World" }
},
components: { fred }                                 
});

Index.html

<!doctype html>
<html>
<head>
  <script src="scripts/vue.min.js"></script>
  <script data-main="scripts/build/index" src="scripts/lib/require.min.js"> 
  </script></head>
   <body>
     <div id="app"></div>
   </body>

tsConfig

{"compileOnSave": true,
"compilerOptions": {
"module": "amd",
"moduleResolution": "node",
"noImplicitAny": true,
"noEmitOnError": false,
"outDir": "./scripts/build",
"removeComments": false,
"sourceMap": true,
"target": "es5",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
},
"exclude": [
"node_modules",
"wwwroot"
],
"include": [
"./scripts/**/*"
]

}

Answer №1

When you write this code snippet:

Vue.component('apple2', Apple.default);

You are essentially associating the component definition object (Apple.default) with the name apple2 in the global Vue instance, allowing all components rendered by that Vue instance to access it. To simplify your code in index.ts, you can remove the following section:

components: { Apple}

Your app should still function correctly in theory.

However, if you utilize TypeScript, you have the option to structure your app as if it were using a module system. This enables you to import sub-components into each parent component, like so:

App.ts

export default const component = {
    template: '<div>My component</div>'
}

index.ts

import Vue from 'vue';
import component from './App';

new Vue({
    el: '#app',
    components: {
        'my-imported-component': component
    }
});

Within your template:

<div id="app">
    <my-imported-component/>
</div>

This approach may be more favorable as it avoids cluttering the global Vue instance with numerous components. Ultimately, the choice between methods depends on personal preference and the requirements of your project.

For further details, refer to the following link:
https://v2.vuejs.org/v2/guide/components-registration.html

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

Utilizing files that do not have the extension '.ts' or '.tsx' within the 'ts_library' as dependencies

My current challenge involves importing a JSON file from TypeScript while utilizing the resolveJsonModule flag in my tsconfig. The problem lies in how I can provide this JSON file to ts_library since it seems unable to locate the file. This issue extends t ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Understanding the concept of mutable properties in Typescript

Why can the property 'name' in the class 'PersonImpl' be reassigned even though it is not declared as read-only in the Person interface? interface Person { readonly name: string; } interface Greeting extends Person { greet( ...

Compiler error occurs when trying to pass props through a higher-order component via injection

Recently, I have been experimenting with injecting props into a component using a higher order component (HOC). While following this insightful article, I came up with the following HOC: // WithWindowSize.tsx import React, {useEffect, useMemo, useState} fr ...

Angular - optional parameter in route using ngRouter

I have a question regarding using Angular (4) with the @angular/router. I want to be able to include optional parameters in a path style, but am facing some challenges. Currently, my code looks like this: { path: 'cars', component: CarComponent ...

Tips on personalizing the default html template in nuxt

Struggling to customize the default page from my Nuxt app due to limited documentation. Link to Documentation I'm interested in extracting only certain elements like the title or links in the head section. For example, how can I access just the li ...

Async function causing Next JS router to not update page

I'm diving into the world of promises and JavaScript, but I've encountered an issue while working on a registration page following a tutorial on YouTube. Currently, I am using next.js with React and TypeScript to redirect users to the home page i ...

Storing the output of a GET request in a text file can lead to a never-ending loop

After attempting to save a String obtained from a GET request into a text file, I encountered an unexpected infinite loop issue. It seems that without utilizing created(), the process fails entirely, resulting in story remaining empty. <div id="app"> ...

A guide on implementing react-pose alongside @reach/router in a React Typescript project

I'm facing a challenge in my React app as I attempt to convert a JS example using react-pose and @reach/router to TypeScript, but unfortunately, it's not functioning properly. Below are the relevant typings from react-pose: import { ComponentTy ...

Is there a way to disable Google fonts and Material Design icons in Vuetify?

I'm working on an internal app for our company that operates offline, so I can't utilize CDNs or Google Fonts. When checking my developer console in Chrome (oddly not in Firefox), I see errors indicating the use of the following URLs: and In N ...

Troubleshooting: Vue.js custom select element not responding to blur event

Unique Scenario A custom autocomplete select component has been created that not only autocompletes but also allows for adding a new value if the result is not found. This functionality was discovered to be missing in the vue-select module. Explore the C ...

Automating the linking of tsd definitions with bower and npm: A step-by-step guide

Currently, I am in the process of transitioning an existing project to TypeScript which includes numerous bower and npm dependencies (bower.json and package.json). As mentioned on the tsd github page, TSD facilitates the discovery and linking of defini ...

The text color remains the same even after the method has returned a value

I have a vuex query that returns a list of books. I want to display each book with a specific color based on its status. I tried using a method to determine the color name for each book and bind it to the v-icon, but it's not working as expected - no ...

Does the data in a Vuex store always stay in memory?

Firstly, I want to thank you for your patience with my limited English skills. I am curious if the data in Vuex's store always stays in memory. Let me provide an example. If we receive a list from the server and store it in the Vuex state when enteri ...

Create a const assertion to combine all keys from an object into a union type

I am working with an object similar to this (demo link): const locations = { city: {name: 'New York'}, country: {name: 'United States'}, continent: {name: 'North America'} } as const My goal is to create a union t ...

Using type aliases in Typescript to improve string interpolation

After working with Typescript for some time, I have delved into type aliases that come in the form: type Animal = "cat" | "dog"; let a1_end = "at"; let a1: Animal = `c${a1_end}` I initially thought that only the values "cat" ...

"Using VueX to update an array of data in the state object

Trying to wrap my head around VueX and its potential here. Currently grappling with the concept of a state object array named currentRoom which ideally should only hold one object at a time. The issue is that instead of replacing the current room data when ...

"Implementing a retry feature for Angular http requests triggered by a button

Imagine having a situation where a component has a method that triggers an http request defined in a service. The observable is subscribed to within the component: Component: fetchData() { this.apiService.fetchDataFromServer().subscribe( respo ...

Failed to successfully retrieve JSON data

Here is a code snippet that calls a translator API: var url = "https://api.lingo24.com/mt/v1/translate"; $.getJSON(url + "?user_key=9e56f5d5e5b5647a32ccb58f7bcd8327&q=test&source=en&target=fr&callback=callback", function (data) { ...

Guide on transmitting data from a child component to a parent object in Vue.js?

When I attempt to utilize a child component with custom form inputs and emit those values to the parent component, I encounter an issue where one input value disappears when another input value is entered. Let me showcase some code: Child Component <tem ...