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

Adding a second interface to a Prop in Typescript React: a step-by-step guide

import { ReactNode, DetailedHTMLProps, FormHTMLAttributes } from "react"; import { FieldValues, SubmitHandler, useForm, UseFormReturn, } from "react-hook-form"; // I am looking to incorporate the DetailedHTMLProps<FormHTMLAt ...

Capturing content from an HTML node and integrating it into VueJS data

<tasks> @foreach ($task as $tasks) <task>{{ $task->name }} [{{ $task->completed }}]</task> @endforeach </tasks> This snippet shows how I display a list of tasks from the database. Here is my Vue component setu ...

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...

Customize Nuxt default document using a custom app.html file

According to the guidelines provided by Nuxt documentation, you have the ability to customize the default document by... placing an app.html file in the source directory of your project, which is typically the root directory. I followed these instructio ...

Binding an ID to an <ion-textarea> in Ionic 3

Can an ID be assigned to an ion-textarea? For example: <ion-textarea placeholder="Enter your thoughts" id="thoughtsBox"></ion-textarea> Thank you very much ...

Simultaneous Push and Insert operations with Vue.js and PHP

I am looking to add a value into an Array and have it displayed instantly without the need to refresh the entire page. app.todoList.push(this.todo) This line accomplishes that task. Simultaneously, I also want to insert this value into a Database. The i ...

The Typescript error message states that the type '{ onClick: () => void; }' cannot be assigned to the type 'IntrinsicAttributes'

I'm a beginner in Typescript and I'm encountering difficulties comprehending why my code isn't functioning properly. My goal is to create a carousel image gallery using React and Typescript. However, I'm facing issues when attempting t ...

Determine parameter types and return values by analyzing the generic interface

I am currently working on a feature where I need to create a function that takes an interface as input and automatically determines the return types based on the 'key' provided in the options object passed to the function. Here is an example of ...

Is it necessary to mock the HTML5 audio element when unit testing with Jest in vue.js?

Exploring the functionality of an AudioPlayer vue component that includes the HTML5 element, I am contemplating how to structure my specifications using Jest. template <audio id="player" ref="player" @ended="ended" @canplay="canPlay" :src="file"& ...

The v-model attribute is not properly passing through to the child component

I have created a custom <select> component: <!-- Select.vue --> <template> <div class="select" inheritAttrs="false"> <select v-bind="$attrs"> <slot></slot> </select ...

Adjust the scroll position when the height of a div is modified

Imagine we have a large div A with a height value and below it are other divs B, C, and more. If the user is viewing divs B or C, and A reduces its height by half, the scrolling position will remain the same. However, divs B and C will move up by that amo ...

Exploring Touch Interactions in Vue.js 2.0

Recently I started working with Vue 2.0 and encountered the need to incorporate swipe gestures into my project. After exploring the official plugin called vue-touch, I discovered that it does not currently support Vue 2.0. Can anyone recommend alternative ...

How to pass an array as parameters in an Angular HTTP GET request to an API

Hey there! I'm relatively new to Angular and I've hit a roadblock. I need to send an array as parameters to a backend API, which specifically expects an array of strings. const params = new HttpParams(); const depKey = ['deploymentInprogre ...

Using VueJS: Automatically scroll to a specific line in a table when the page loads

In my element framework table, I have a list of questions. I can select one to edit, make changes, and after validating, I want the page to automatically scroll to the modified question. <template> <div> <el-table :data="lis ...

Warning: Typescript is unable to locate the specified module, which may result

When it comes to importing an Icon, the following code is what I am currently using: import Icon from "!svg-react-loader?name=Icon!../images/svg/item-thumbnail.svg" When working in Visual Studio Code 1.25.1, a warning from tslint appears: [ts] Cannot ...

The HTTP DELETE request encountered a TypeError, stating that error.json is not a valid function

Within my Angular application, there is a feature that involves a "delete button". When this button is clicked, a confirmation popup appears asking the user if they are certain they want to proceed with the deletion. If the user confirms by clicking ' ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

I am encountering an issue with Wedriver.IO where screenshots of executions on a Remote Selenium Grid Hub are not being included in my Allure Reports

wdio.conf.ci.js: The following code snippet has been added. afterTest: function(test, context, { error, result, duration, passed, retries }) { if (passed){ browser.takeScreenshot(); } }, I expect to see a screenshot attachment in the bottom right corn ...

Is it possible to blend Laravel with the Vue-storefront template?

Can Laravel 5.7 be combined with the Vue template available at: https://github.com/DivanteLtd/vue-storefront ? ...

What is the most effective way to retrieve the value of a child component in Angular 2 and pass it to the parent component?

I am working on a project with a child component (calendar) and a parent component (form). I need to select a value in the calendar and then access that value in the form component. What is the best way to achieve this? Child Component.ts: import { ...