Navigating with Routes in Vue.js using TypeScript

I recently began working on a new Vue.js project after a long break from using it, and I noticed some significant changes. I attempted to add a route in my src/router/index.ts file (shown below), but when I visited localhost:8080 to see my beautiful HelloWorld.vue component, I was greeted with the content of my Simulator.vue, displaying "Yooood."

How is this possible? The base path of my app accessed via "/" should display the HelloWorld.vue component with only a "Hello World" text...

When trying to access /simulator using a

<router-link to="/simulator">Go to Simulator</router-link>
, I still saw the same content...

I am quite confused. Below are my files.

router/index.ts

import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import Home from '../views/Home.vue'
import Simulator from "@/components/Simulator.vue";
import HelloWorld from "@/components/HelloWorld.vue";

Vue.use(VueRouter);

const routes: Array<RouteConfig> = [
  {
    path: '/',
    name: 'Home',
    component: HelloWorld
  },
  {
    path: '/simulator',
    name: 'Simulator',
    component: Simulator
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

This is my Simulator.vue:

    <template>
        <div class="hello">
            Yooood
        </div>
    </template>
    
    <script lang="ts">
        import {Vue} from "vue-property-decorator";
    
        export default class Simulator extends Vue {
    
            mounted() {
                console.log('mounted');
            }
        }
    </script>
    
    <style scoped>
    
    </style>

And here is my HelloWorld.vue

    <template>
      <p>
        Hello World
      </p>
    </template>
    
    <script lang="ts">
    import { Component, Prop, Vue } from 'vue-property-decorator';
    
    @Component
    export default class HelloWorld extends Vue {
      @Prop() private msg!: string;
    }
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped>
    h3 {
      margin: 40px 0 0;
    }
    ul {
      list-style-type: none;
      padding: 0;
    }
    li {
      display: inline-block;
      margin: 0 10px;
    }
    a {
      color: #42b983;
    }
    </style>

Lastly, my App.vue

    <template>
      <div id="app">
      </div>
    </template>
    
    <script lang="ts">
    import {Vue } from 'vue-property-decorator';
    
    export default class App extends Vue {}
    </script>
    
    <style>
    #app {
      font-family: Avenir, Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>

Answer №1

Make sure to include the router-view component in your code. As per the documentation from vue-router here,

The <router-view> component is essential as it renders the component that matches the specified path

APP.vue

<template>
  <div id="app">
    <router-view></router-view> // remember to add the router view component here
  </div>
</template>

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

Retrieve TypeScript object after successful login with Firebase

I'm struggling with the code snippet below: login = (email: string, senha: string): { nome: string, genero: string, foto: string;} => { this.fireAuth.signInWithEmailAndPassword(email, senha).then(res => { firebase.database().ref(&ap ...

Exploring Angular 6: Understanding the Reflect API within the polyfills.ts File

The file polyfills.ts includes a commented out line that states: /** IE10 and IE11 requires the following for the Reflect API. */ // import 'core-js/es6/reflect'; Can you explain what the 'Reflect API' is? Why is it needed for Interne ...

Top pick for error status codes in single-page application

I'm interested in creating a SPA application using Vue and Laravel. When it comes to returning errors, I have two options... which do you think is the better choice? Option 1: return response(['message'=>'page not found'] , 40 ...

Mapping a Tuple to a different Tuple type in Typescript 3.0: Step-by-step guide

I am working with a tuple of Maybe types: class Maybe<T>{ } type MaybeTuple = [Maybe<string>, Maybe<number>, Maybe<boolean>]; and my goal is to convert this into a tuple of actual types: type TupleIWant = [string, number, boolea ...

How to set up a Vue.js route to link to an XML file instead of a .vue file

I need to set up a route in vue-router that points to an XML file for the purpose of submitting a sitemap.xml to Google search console. I have been unable to find a solution for creating a .xml url with vuejs using vue-router. Currently, each route corresp ...

Angular Material table pagination is not functioning properly

I'm in the process of building a table using Angular Material Table My goal is to incorporate pagination into the table so that users can easily navigate to their preferred page, similar to this example: Material data table This is what I have achi ...

Is there a way to make the Sweetalert2 alert appear just one time?

Here's my question - can sweetalert2 be set to only appear once per page? So that it remembers if it has already shown the alert. Swal.fire({ title: 'Do you want to save the changes?', showDenyButton: true, showCancelButton: true, ...

Exploring the vue property realm

Within my authority system, I securely store a secret token in Vue fields and retrieve it from localStorage during the created event: const app = new Vue({ router: router, data: { token: '', user: null, }, created ...

Issue with Switch Map in Angular 2 and RxJS

I'm currently implementing an infinite scrolling feature in my application using a specific component for managing scroll events. When the scroll reaches the bottom of the div, I trigger a function to fetch more data. Everything seems to be working fi ...

Guide on obtaining Elastic search documents in the specified order of identifiers

Given a specific order of document IDs [1, 4, 2, 5] and some filtering criteria { match: {...} }, what is the most efficient method to ensure that the resulting documents are retrieved in the desired order [1, 4, 2, 5]? Here is an example of a sample docu ...

Guide on retrieving the response value from the httpclient in Angular 6

I am utilizing HttpClient for sending requests. I have created a service to handle this. import { Injectable } from '@angular/core'; import { HttpClient, HttpParams, HttpHeaders, HttpResponse ,} from '@angular/common/http'; import {Obs ...

Best practice: Implementing OAuth2 with PHP server in Vue applications

I am currently implementing OAuth2 logic in PHP using . I would like to know the best practices for incorporating OAuth2 validation with the Vue framework. I have heard that the Implicit grant type was previously used, but due to security concerns, it is ...

Jasmine and Karma encountered a TypeError stating that the function this.role.toLowerCase is not valid

Currently, I am in the process of writing a test case for a page within an application that our team is actively developing. However, I have encountered a challenging error within one of the test cases that I am struggling to overcome. Below is my Spec fil ...

Are the Cypress .trigger() and .type() functions capable of simulating a true keydown event?

Our Vue 2 app is responsible for managing a form and its submission process. Within the Vue app, there exists a method that deals with the input field for entering a credit card expiration date. <input v-model="expDate" type="te ...

"Discovering the root cause of Angular memory leaks and resolving them effectively is crucial for

I am facing an issue with a code that appears to be leaking, and I am seeking advice on how to identify the cause or properly unsubscribe. Even after adding an array containing all object subscriptions, the memory leakage persists. import { Component, On ...

What is the best way to manage files in Vue.js?

I am faced with a challenge in storing image files and video files as Blob data. One thing I like is that the uploaded video and image files display instantly, which is pretty cool. I'm not entirely sure if the code below is correct - how can I navi ...

Encountered an issue: The type 'Usersinterface' is not meeting the document constraints

Below is a screenshot displaying an error: https://i.stack.imgur.com/VYzT1.png The code for the usersinterface is as follows: export class Usersinterface { readonly username: string; readonly password: string; } Next, here is the code for users ...

The attribute 'XXX' is not found within the type 'IntrinsicAttributes & RefAttributes<any>'

My coding hobby currently involves working on a React website using TypeScript. I recently came across a free Material UI template and decided to integrate it into my existing codebase. The only challenge is that the template was written in JavaScript, cau ...

A guide to incorporating Lodash into TypeScript and Webpack without overriding the current _ variable

Currently, I am in the process of developing a module for an application that is utilizing Lodash 3. However, I would like to upgrade to Lodash 4 in this new module. This particular module is being coded in TypeScript and bundled with Webpack. Initially, ...

Creating a flexible TypeScript function handler that accepts optional arguments depending on the function's name

I am facing a challenge with defining the function type for running helper functions that prepare database queries. Some of these functions have arguments, while others do not. TS Playground Link type PreparedQuery = { query: string; params?: string[] ...