Vue will display only the most recent component that has been registered

In Vue, it always renders the last registered component and ignores any others, even if they are not used at all.

//main.ts
import Vue from 'vue';
Vue.component('component-one', require('./components/ComponentOne.vue'));
Vue.component('component-two', require('./components/ComponentTwo.vue'));

const app = new Vue({
    el: '#app1',
    vuetify,
})
//ComponentOne
<template>
  <h2>Component One</h2>
</template>
<script lang="ts">
import Vue from 'vue'
export default class ComponentOne extends Vue{ 
}
</script>
//ComponentTwo
<template>
  <h2>Component Two</h2>
</template>
<script lang="ts">
import Vue from 'vue';
  export default class ComponentTwo extends Vue{
  }
</script>
<body>
   <div id="app1">
      <!-- No matter what I put here, only the last registered component will be displayed -->
      <h2>Title</h2>
      <component-one></component-one>
      <component-two></component-two>
   </div>
   <script src="/js/app.js"></script>
</body>

The page is rendering the content of ComponentTwo instead of ComponentOne. See a screenshot here.

If I remove the component registration lines, I can use external component libraries (like Vuetify) inside the div tag, but this restricts my custom components. I had expected to freely use both custom and external components within the same div tag.

Edit: Thank you for the responses. Is there a way to incorporate these components into the HTML element as if they were part of a template? Something like:

<!-- This could be an index.html or, in my case, a Laravel Blade view
<body>
   <div id="app1">
      <component-one></component-one>
      <component-two></component-two>
   </div>
   <script src="/js/app.js"></script>
</body>

Vuetify components function correctly following this approach if no custom components are registered.

Answer №1

What is the reason behind using a javascript main.js instead of a main.ts file?

Here is an example of a standard main.ts app mount function. The element #app is being renamed to #app1

import Vue from 'vue';

new Vue({
    render: (h) => h(App)
}).$mount('#app');

By mounting the main .vue instance, you can then render any components you want. Below is a small example that incorporates some of your code along with the helpful tool vue-property-decorator, which although not mandatory, can be very useful when working with Typescript and Vue.

<template>
  <div>
   <body>
    <div id="app1">
      <h2>Title</h2>
      <component-one></component-one>
      <component-two></component-two>
     </div>
    </body>
  </div>
</template>


<script lang="ts">
    @Component({
        components: {
            // This demonstrates lazy loading components, but you could also import them traditionally above the @component decorator
            'component-one': () => import('@/components/ComponentOne.vue').then(m => m.default),
            'component-two': () => import('@/components/ComponentTwo.vue').then(m => m.default),
        }
    })
    export default class App extends Vue {}
</script>

Answer №2

When working with Vue, it's important to designate the initial component to be displayed in your main.js file. Here is an example:

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

new Vue({
  el: '#app',
  render: h => h(App),
})

Once you have defined the first component (in this case, App.vue), you can then proceed to import additional components within that main component, such as ComponentOne.vue and ComponentTwo.vue.

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

What strategies can be employed to improve generic inference skills?

Looking at the scenario provided below, how can we enhance code reusability in a manner similar to foobarA? interface F<T, U extends string> { t: T, f: (u: U) => void } declare const foo: <T, U extends string>(type: U) => F<T, U>; ...

Creating a generic anonymous class in TypeScript can be achieved by specifying the class body

The title might be a bit misleading, but I'm struggling to articulate my issue. I aim to pass a generic class (or just the class body) as an argument to a function. The provided class should then infer its generics automatically. class Builder<EX ...

Struggling to customize Vuetify styles with my own stylesheet

In my current project, I am utilizing Vue2 and Vuetify. One of the main challenges I am facing is that my Vuetify styles are always imported after my own custom styles. I attempted the following: App.vue <template> <v-flex> <v-c ...

The ion-col with col-3 is causing a template parse error

Currently, I am facing an issue while trying to print data from a constructor. Everything is working fine until I added col-3 to ion-col. It seems like I missed including some module, but I am not sure which one. This is my home.ts file: import { Compone ...

Exploring the functionality of publicRuntimeConfig in Nuxt plugins

I have developed a new Vue socket.io plugin called @/plugins/socket-io.js import Vue from 'vue' import VueSocketIO from 'vue-socket.io' Vue.use( new VueSocketIO({ debug: true, connection: process.env.SOCKET_IO_CONNECTION, } ...

Encountering a sort error in Angular 8 when attempting to sort an Observable

I am struggling to organize an observable that is retrieved from a service using http.get. I have attempted to sort the data both from the service and in the component after subscribing. However, I keep encountering the error "Sort is not a function". As ...

What is the best way to incorporate server-side rendered content from a CMS to hydrate Vue.js?

Consider this scenario: content is managed through a traditional CMS such as Joomla or Drupal content is provided by the CMS as fully rendered HTML and CSS In the Frontend React.js should be utilized for all UI interactions. Despite going over most of R ...

The Vue feature responsible for displaying information on the webpage is currently not working as expected

I'm in the process of developing a settings page for a project. This particular page is based on HTML and utilizes JSON to store data, with Vue 3 being used to display the information on the page. However, I've encountered an issue where the data ...

My initial experience with vue.js has been complicated by issues with routers

I've recently dipped my toes into the world of Javascript and vue.js. After following a tutorial on creating a single page shopping application, I decided to incorporate routers into my learning project. However, I encountered some interesting error ...

How do I fix the build error that says "Operator '+' cannot be used with types 'number[]'?

The function below is designed to generate unique uuidv4 strings. function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => ( c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)) ...

Enabling CORS for jsonplaceholder website

Currently, I am delving into learning Vue and experimenting with making API calls using Axios to my local Django server. As a result, I have come across CORS errors. Despite my understanding of how CORS functions and why it might be blocking my calls, I fi ...

Determine whether something has the potential to be a string in TypeScript

I am looking to create a TypeScript type that can identify whether an element has the potential to be a string. This means the element should have the type "string" or "any", but not "number", "boolean", "number[]", "Person", etc. I have experimented wit ...

Encountering an issue when attempting to attach an event listener to the entire document

I need help troubleshooting an issue with a function that is supposed to perform certain operations when the scrollbar is moved. I attached an event listener to the document using an ID, but it's resulting in an error. ERROR Message: TypeError: Canno ...

Ways to retrieve a value from a span using the Document Object Model

sample.html <span id='char'>{{value}}</span> sample.ts console.log((<HTMLInputElement>document.getElementById('char'))) This code snippet will display <span id='char'>ThisIsTheValueupdated</sp ...

Enhance mix-blend mode or filtering effects in SCSS using an SVG component in VueJS

I am currently developing a fixed navbar at the top of a webpage with several SVGs inside anchor tags. I want the SVGs to appear black when displayed over lighter colored divs (other Vue components) and white when displayed over darker colored ones. The ba ...

Encountering issues following the integration of @angular/flex-layout into an Angular project

After careful consideration, I opted to utilize the responsive grid system provided by @angular/flex-layout instead of Bootstrap. By simply installing the npm package and adding it to my AppModule, I was able to integrate it seamlessly: import { NgModule ...

Struggling with defining types in NextJs when using dynamic imports in Typescript and NextJs

I have successfully created a component that utilizes next/dynamic to import react-icons only when needed. However, I am struggling to properly define the TypeScript types for this component. Despite this issue, the component itself is functioning as expec ...

Facing issue in Visual Studio 2015 with Angular 2 @component not able to resolve the signature of the class decorator

Trying to define a decorator on top of my class in Visual Studio 2015 is causing an error during the build process. The specific error message states: "Build: Unable to resolve signature of class decorator when called as an expression." import { Component ...

Exploring the dynamic duo of Github and vue.js

As I am new to programming and currently learning JavaScript and Vue.js, I have been trying to deploy my first Vue.js app without success. Despite spending hours on it, I still cannot figure it out and need to seek assistance. Every time I try to deploy, ...

Strategies for resolving type issues in NextJs with Typescript

In my project using Next.js with TypeScript, I encountered an issue while trying to utilize the skipLibCheck = false property for enhanced checking. This additional check caused the build process to break, resulting in the following error: Error info - U ...