The Vue router fails to load when using create-vue@3

I've been experimenting with the Vue Router, but it's not giving me the expected outcome.

While following the tutorial on https://router.vuejs.org/guide/, I found that if I use the CDN and place it in a standalone HTML file, it works fine. However, when I try to implement it in this way, it doesn't work as intended:

Steps for Reproduction:

  • Run npm create vue@3
  • Configuration:
    • Project name:... vue-project
    • Add TypeScript? Yes
    • Add JSX Support? Yes
    • Add Vue Router for Single Page Application development? Yes
    • Add Pinia for state management? No
    • Add Vitest for Unit Testing? No
    • Add an End-to-End Testing Solution? No
    • Add ESLint for code quality? No
  • Install all dependencies
  • Change src/main.ts to
import * as Vue from 'vue'
import * as VueRouter from 'vue-router'

// 1. Define route components.
// These can be imported from other files
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }

// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
//   { path: '/smm', component: About },
]

// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = VueRouter.createRouter({
  // 4. Provide the history implementation to use. We are using the hash history for simplicity here.
  history: VueRouter.createWebHashHistory(),
  routes, // short for `routes: routes`
})

// 5. Create and mount the root instance.
const app = Vue.createApp({})
// Make sure to _use_ the router instance to make the
// whole app router-aware.
app.use(router)

app.mount('#app')
  • Change index.html to
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>
  </head>
  <body>

<div id="app">

    <h1>Hello App!</h1>
    <p>
      <!-- use the router-link component for navigation. -->
      <!-- specify the link by passing the `to` prop. -->
      <!-- `<router-link>` will render an `<a>` tag with the correct `href` attribute -->
      <router-link to="/">Go to Home</router-link>
      <router-link to="/about">Go to About</router-link>
    </p>
    <!-- route outlet -->
    <!-- component matched by the route will render here -->
    <router-view></router-view>
</div>

    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

- run `yarn start`

Versions of Vue and vue-router being used:

  "dependencies": {
    "vue": "^3.3.2",
    "vue-router": "^4.2.0"
  },

Answer №1

To properly integrate Vue into index.html, it is recommended to move all content within the <div id="app"> tag into a .vue Single File Component (SFC).

index.html

<body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
</body>

App.vue

<template>
  <h1>Hello App!</h1>
  <p>
    <router-link to="/">Go to Home</router-link>
    <router-link to="/about">Go to About</router-link>
  </p>
  <router-view></router-view>
</template>

<script setup></script>

After creating the SFC, import it into main.ts and set it as the root component using createApp().

main.ts

import App from './App.vue'
import { createApp } from 'vue'
.
.
.
const app = createApp(App)
app.use(router)

app.mount('#app')

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

Uploading files and data in Laravel using Vue.js and Vuetify: A step-by-step guide

My Vuetify form is working fine with text input, but when I try to include images, I encounter the error GET http://danza.test/thumbnails[object%20File] 404 (Not Found). How can I successfully pass both text and images in a form? This is part of the code ...

Function arity-based type guard

Consider a scenario where there is a function with multiple optional parameters. Why does the function's arity not have a type guard based on the arguments keyword and what are some solutions that do not require altering the implementation or resorti ...

Establish a connection to the ActiveMQ broker utilizing STOMP protocol in an Ionic application

I've recently received an Ionic + Capacitor app that is primarily meant to run on the Android platform. My current task is to incorporate communication with a remote ActiveMQ broker into the app. To achieve this, I utilized the STOMP JS library which ...

Interactive Angular Interfaces Featuring Numerous Numeric Choices Within the Main Object

I am currently in the process of designing an interface for my Angular project that allows users to search for video games using the WhatToPlay API within RapidAPI. When a user searches for details on a video game, the result will return a game identified ...

Finding the precise directory of a local JSON file for an Axios GET request in Vue.js

In my Vue project, I have prepared some dummy data for future development. The test data is stored in a `json` file, and my Vue project follows the typical structure created with Vue-Cli: My_project build config data service_general_in ...

What is the best way to incorporate styled components and interpolations using emotion theming?

I've been building a React web application with a dynamic theme feature using the emotion-theming library. This allows users to switch between different environments, each with its own unique theme. To achieve this, I created my own CustomThemeProvide ...

How to use Angular 2 to communicate with JavaScript API whenever the router switches to

I am currently working on an Angular2 component that has a template which relies on JavaScript calls to load various components such as Facebook, Google Maps, and custom scripts. The necessary scripts are already loaded in the index.html file, so all I ne ...

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...

Error: The identifier HTMLVideoElement has not been declared

Encountering an issue while attempting to build my Angular 9 Universal project for SSR: /Users/my-project/dist/server.js:28676 Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__metadata"])("design:type", HTMLVideoElement) ReferenceError: HTMLVideoElem ...

The term 'Component' is not a valid JSX component that can be used

'Component' is causing issues as a JSX component The error appears to be within the _app.tsx file of my Next.js project. I've been struggling with this problem since yesterday, encountered it during deployment on Vercel for my Next.js TypeS ...

Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one compo ...

Is there intellisense support for Angular 2 templates in Visual Studio?

Is it possible for Visual Studio to provide autocomplete suggestions for properties of a Typescript component within a separate HTML view template? ...

Leveraging functionality from an imported module - NestJS

Currently, I am utilizing a service from a services module within the main scaffolded app controller in NestJS. Although it is functioning as expected - with helloWorldsService.message displaying the appropriate greeting in the @Get method - I can't ...

Enhance the efficiency of writing the *.d.ts file

I have recently started diving into TypeScript with React and encountered a new concept called a .d.ts file. I am wondering if there is an established best practice for writing this file or if it's more of a developer preference. Can someone verify if ...

Transform current JSON data into formatted JSON format using JavaScript or TypeScript

I have a JSON structure that needs to be reformatted in order to meet the requirements of an external service. Although the current format is complex and cannot be altered, I need to modify it to match the desired output for the external service. Current ...

Convert the button element to an image

Can someone please explain how to dynamically change a button element into an image using javascript when it is clicked? For instance, changing a "Submit" button into an image of a check mark. ...

Exploring SVG Morphing Reversal Techniques in Anime.js

I have been trying to implement direction: 'reverse' and timeline.reverse(), but so far it hasn't been successful. Interestingly, when I set loop: true, the reverse animation can be seen within the loop. However, my goal is to trigger this a ...

The type mismatch issue occurs when using keyof with Typescript generics

One of the challenges I am facing is related to an interface that stores a key of another interface (modelKey) and the corresponding value of that key (value): interface ValueHolder<T, H extends keyof T> { modelKey: H; value: T[H]; } My objectiv ...

Convert a file to base64 using the v-file-input component in Vue.js with Vuetify

vue.js: <input type="file" @change="encodeFileToBase64" accept=".pdf, .docx"> </input> Is there a simple method to convert a file to base64 encoding in Vue.js? ...

Interacting with Vue3 List Items by Manipulating the HTML DOM

I am currently using Vue 3 and I have a requirement to manipulate a specific list item when a button is clicked. Below is the HTML code snippet: <socialDiv v-for="(follower, i) in followerList" :key="follower.id" :ref="el => ...