What is the best way to properly redirect a page using a router link in Vue.js 2?

I've encountered an issue with the router-link component in Vue.js 2. I have set up my router file

index.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';
import OrdersView from '../views/OrdersView.vue';

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/order',
      name: 'order',
      Component: OrdersView
    }
  ]
   
  const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

export default router;
})

HomeView.vue

<template>
    <p>HomeView</p>
</template>

<script>
  export default {}
</script>

OrdersView.vue

<template>
    <p>OrdersView</p>
</template>

<script>
  export default {}
</script>

App.vue

<template>
  <div id="app">
    <div class="sidebar-sticky pt-3">
        <ul class="nav flex-column">
          <li class="nav-item">
            <router-link to="/order">Orders</router-link>
          </li>
        </ul>
    </div>
    <div class="container-fluid">
       <div class="row">
        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-md-4">
         <router-view/>
        </main>
       </div>
    <div>
  </div>
</template>

When launching my application, I encounter an error where clicking on the router link for Orders does not display the content of OrdersView in the router-view section of App.vue.

If anyone can assist me in understanding why the content of OrderView.vue is not being displayed in the app.vue (router-view section), that would be greatly appreciated.

Answer №1

Your index.js file for the router is filled with various syntax errors that need to be addressed.

  1. Ensure that when using the Vue.use() function, you pass in the VueRouter object instead of just Router.

  2. Avoid creating a Router object as it is not a valid entity.

  3. It's not permitted to export two default values from your file.

  4. Do not attempt to export the router object if it is out of scope.

Once these corrections are made, your code should resemble the following structure:

import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';
import OrdersView from '../views/OrdersView.vue';

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/order',
    name: 'order',
    Component: OrdersView
  }
]

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

export default router

If you're not already using an IDE like Visual Studio Code with the Vetur extension, I recommend doing so. These tools can help you catch and correct errors in your code before running your application.

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

Tips for fetching a particular item from a getItem dynamoDB in JavaScript

I am trying to retrieve an item from my AWS database. The item 'test2' is printing correctly in my console. However, I want to extract an attribute or variable from this item and store it as a variable named test. How can I accomplish this? For i ...

Unable to input information into Textbox in real-time

Having trouble entering data from one page to another using ng-model. After filling in some information in a textbox and moving to the next page, I want the same data to be entered when I return to the previous page. I've written the code but it doesn ...

The npm http package exclusively includes a package.json without any accompanying JavaScript files

After installing an npm package that listed 'http' as a dependency, I also installed 'http'. However, all npm downloaded for 'http' was a package.json file that referenced a non-existent index.js file. Could it be that the ind ...

Using a variety of objects in TypeScript arrays

How to effectively implement a superior class in TypeScript for an array containing diverse objects that inherit from the same class, without triggering errors? This is my attempt: interface IVehicle{ modelName: string } interface ICar extends IVehi ...

the mobile website is not properly aligned on a horizontal axis

As I work on creating a mobile version of my website, I've come across a challenge: The entire site fits perfectly on the computer at a browser width of 480px, but when viewed on my mobile phone (regardless of the browser used), it leaves space on the ...

Creating a structure object in a Laravel controller for implementing Vue.js autocomplete functionality

I am currently facing an issue with my autocomplete feature not displaying options correctly. To start off, I am fetching hard coded data from my controller and passing it through an axios call: searchController.php $searchResults = [ 0 => (ob ...

Struggling to implement touch event functionality for CSS3 spotlight effect

I'm experimenting with implementing touch events on an iPad to achieve a certain effect. Currently, I have it working smoothly with mouse events on JSFiddle at this link: http://jsfiddle.net/FwsV4/1/ However, my attempts to replicate the same effect ...

Wait until the user submits the form before activating Angular validations, and do not display any validation messages if the user deletes text from a text box

I am looking to implement angular validations that are only triggered after the user clicks on submit. I want the validations to remain hidden if the user removes text from a textbox after submitting it. Here is what I need: - Validations should not be dis ...

Converting JavaScript JSON into a PHP array

When working with Javascript, I create an array using the following code: cachePHP = "'lat':'" + (Number(upDataItems[2])).toFixed(5)+"'"; cachePHP = cachePHP + ",'lon':'" + (Number(upDataItems[3])).toFixed(5)+"' ...

Determine the outcome of the assessment quiz

Greetings everyone, I apologize for my poor English. I've been searching through numerous documents, but due to my language barrier, I am having trouble understanding them. I have designed a quiz page, but I'm facing an issue where I can't d ...

One limitation is that you cannot use JQuery to make multiple rows editable simultaneously

I have a unique challenge with implementing an edit button on each row of a dynamic Bootstrap table. I am attempting to toggle the button's icons and, depending on its current state, enable the corresponding row for editing. <td><button typ ...

Adjusting the size of all elements on a webpage

Upon completing my project, I noticed that my localhost:3000 is zoomed in at 125%, causing it to appear less than ideal at 100% zoom. Is there a way to adjust the zoom/scale of my website to match how it appeared on my localhost environment? I came across ...

What is the best way to set an object's value to null in AngularJS?

Check out this code snippet var data={}; data={stdId:"101"}; data={empId:"102"}; data={deptId:"201"}; In my project, I'm receiving data from services into a data object with differing key names such as stdId or empId, etc. I need to set empty val ...

Error: Unable to access property 'fetch' of null (discord.js)

Hey there, I'm running into an issue where it's giving me an error saying that the property 'fetch' doesn't exist. I'm using the Replit database for a balance command in discord.js. You can see the error image here. Here is t ...

Checking capabilities - Transfer document

I am currently facing an issue with the .setFilesToUpload method while testing an upload screen. Despite trying different approaches, I am unable to successfully upload any files. Upon further investigation, I noticed that selecting a file through the deb ...

Instead of adding a new object to the array, consider increasing the quantity of an existing object

I am new to working with a shopping cart component and my code is structured like this: let cartCount = document.getElementById("counter"); let isItemSelected = false; let itemCount = 0; let shoppingCart = []; let selectedSize = ""; let displaySelectedSiz ...

A tutorial on adjusting camera angles through mouse dragging in Three.js

I have created a unique Rolex cube with varying layers along the "Z axis" and I need to adjust the camera position to preview the geometry accurately. How can I change the camera position by dragging the window and also manipulate individual cone rotations ...

Utilize VueI18n to dynamically translate JavaScript variables into different languages

Trying to show a notification based on a server returned value is my current challenge. I am uncertain about how to dynamically retrieve the translation value using the received key's value. For instance, if the error.response.data.errorDetailsCode v ...

Console displays 'undefined' when using the post method with Node.js/Express

Below is the code for my upload.ejs page: <%- include('header' ,{ title:"Playground" }) -%> <div class="wrapper"> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="text" name="name" place ...

Troubleshooting Problems with Cookie and Session Management

I'm encountering an issue while trying to set cookies and session values during login on the backend, which is built in node js. However, when react calls the API to verify these cookies or session values, they are returning as undefined... My middle ...