Navigating to a different page on Vue2 with routes

I am struggling with redirecting to another Vue page from my script code. I tried using router.push() but it's not directing me to the desired Vue page.

Here is a snippet of my source code:

src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HomePage from '@/components/HomePage'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'IndexPage',
      component: IndexPage
    },
    {
      path: '/homepage',
      name: 'HomePage',
      component: HomePage
    }
  ]
})

src/components/IndexPage.vue

<script>
  import VueRouter from 'vue-router'

  export default {
    name: 'IndexPage',
    methods: {
      redirectUser() { // this method is triggered on button click
         if (1 == 1)
         {
            router.push('/homepage');
            //this.$router.push('/homepage');
         }
      }
    }
  }
</script>

When executing this code, I encounter an error message stating:

ReferenceError: router is not defined at eval

src/main.js

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

Vue.config.productionTip = false

window.Vue = Vue

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

Although I can manually access the link from the browser http://localhost:8080/#/homepage, I'm unable to redirect to it from my script code.

Answer №1

Firstly, ensure you import Vue and VueRouter:

    Vue.use(VueRouter)

Then, in your method:

    this.$router.push({name: 'HomePage'}) 

It's important to remember to import both Vue and Vue Router in order to avoid getting an error like "router is not defined at eval." Additionally, use

this.$router.push('/homepage');

Give it a try by implementing the changes in your src/components/IndexPage.vue file.

<script>
  import Vue from 'vue'
  import VueRouter from 'vue-router'

  Vue.use(VueRouter)

  export default {
    name: 'IndexPage',
    methods: {
      redirectUser() { // this method triggers on button click
        if (1 == 1)
        {
           this.$router.push('/homepage');
        }
      }
    }
  }
</script>

Answer №2

Utilize the component instance property to reach the router:

this.$router.push({name: 'HomePage'}) 

Is this feature included in your application?

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

Answer №3

Thank you for the helpful feedback, my friends. I realized that I had forgotten to import my router file in my Vue project. After making the necessary changes, the updated line of code now reads as follows:

src/components/IndexPage.vue

<script>
  import router from '../router/index.js'  // Added this line and now everything is functioning correctly !!

  export default {
    name: 'IndexPage',
    methods: {
      redirectUser() { // button click triggers this method
         if (1 == 1)
         {
            router.push({name: 'HomePage'})
         }
      }
    }
  }
</script>

Answer №4

If you're looking to redirect users to a different page, consider using this code snippet:

function redirectToPage(url) {
  window.location.href = url;
}

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

Accessing the Div id stored in a session parameter

Is there a way to store the id (div id) into a session variable? This is an example of my code below: <div class='fieldRow'>Options </div> <div id="abcde"></div> <div class='Row'> <?php $user_typ ...

Unable to sort array within a computed property in Vue.JS

Currently, I am working on enhancing my skills in Vue.js and have encountered an issue with sorting arrays in Vue.js. Despite using the sort(a-b) method for ascending order (least alphabet/value first), the array remains unchanged. Even with a function ins ...

Parcel JS: The function tree.render is missing or not defined

Every time I attempt to execute the production build command npm run build or npx parcel build index.html, this error occurs. My project consists of simple HTML and CSS, without any React or third-party libraries. What could be causing this issue? I have t ...

Having trouble debugging the current TypeScript file in VS Code because the corresponding JavaScript file is missing

In my current project using Visual Studio Code version 1.17, I am focusing on debugging the current typescript file. As part of my setup, I have a build task in place which generates a corresponding javascript file structure like so: src/folder1/folder2/m ...

Event triggered when a Socket.IO connection is disconnected

Everything seems to be working well with my code when a new user joins, but I'm encountering issues when a user leaves as it doesn't display anything. Can someone point out the error in my code? Below is my server-side code: const express = requ ...

JavaScript sorting through nested functions

Having an issue with running a function inside another function for my Bingo game script. The checkBingo() function is defined outside of a .click() function, but I'm facing problems. Ajax is involved, so that might be contributing to the issue. Here& ...

Press the button within the table as its name undergoes periodic changes

I am using Python along with Selenium to automate the process of selecting and reserving a room on a website. The site displays a table containing available rooms, and my goal is to locate a specific room and click on the corresponding button within the ta ...

What is the best way to add a new project and make updates to an existing project within an array?

Looking to add a new project and update existing projects within an array. Here's my plan in pseudo-JSON format. How can I update Project A in MongoDB? { _id : ..., userName: milad , projets : [ { .. projectId, pName, location .... A }, ...

Unlocking Extended Functionality in JQuery Plugins

At the moment, I am utilizing a JQuery Plugin known as Raty, among others. This particular plugin typically operates as follows: (function($){ $.fn.raty = function(settings, url){ // Default operations // Functions ...

Displaying checkbox values with JavaScript

How can I display multiple checkbox values when checked in HTML code? Whenever I check a checkbox, I want its value to be shown alongside the previously checked values. Right now, my code only displays one value at a time. Any suggestions on how to achie ...

Traverse the initial three elements of an array using JavaScript (React)

Let's say we have a collection of 5 items: const items = [ {id: 1, name: 'book', price: 50}, {id: 2, name: 'phone', price: 450}, {id: 3, name: 'fish', price: 80}, {id: 4, name: 'apple', price: 5}, {id: 5, name: ...

Looking for tips on how to achieve a sleek search bar expansion effect when focusing using w3.css?

I have been trying to utilize the following code to create a Google search bar that expands when focused within a w3.css navigation bar-item. While it does expand and contract on focus/blur, I am unable to achieve smooth transitions between sizes. The sear ...

Deleting a file and value in JavaScript

Can you help me figure out how to remove the value of q when the .close class is clicked? Here's my code: $(document).on('click', '.close', function () { $(this).parents('p').remove(); }) $('#Q1DocPath'). ...

Creating a text file in Node.js using nodepad formatting

Could anyone assist me with formatting text in a Node.js file to be written to Notepad? Here's the code I'm currently using: const fs = require('fs'); fs.writeFile('write.txt', '', err => {}); var text = [ ...

Having trouble with the functionality of Bootstrap's nav-tabs 'show' feature?

I'm having some issues with adding a search box to my glossary. The glossary is created using nested unordered lists (ul) within another ul that has classes of "nav-tabs" and "bootstrap". In the JavaScript code, I am using the following snippet: $j(& ...

Unique Tags and Javascript: A customized approach

In the process of developing a web application, I am aiming for high standardization. To achieve this goal, I plan to utilize custom namespace tags that will be modified by JavaScript based on their functionality. For instance: <script type="text/java ...

The random quote generator or current tweet quote feature is malfunctioning

I am having trouble with a jQuery on click function that is not working to tweet the current quote. I am working on building a random quote machine and tweeting the current quote is essential. Despite successfully implementing the JSON API, I cannot seem t ...

Retrieve information from a .json file using the fetch API

I have created an external JSON and I am trying to retrieve data from it. The GET request on the JSON is functioning correctly, as I have tested it using Postman. Here is my code: import "./Feedback.css"; import { useState, useEffect } from " ...

React Js: Data not being properly updated in the application state

Presenting App.js - import './App.css'; import { connect } from 'react-redux' import { ActionChangeName } from "./Actions/Action"; function App(props) { return ( <div className="App"> <div> ...

What is the process for assigning a random string value to each document within a mongodb collection using the mongo shell?

Looking to assign a randomly generated string property to every item in a MongoDB collection. Planning to leverage the mongo shell and the updateMany function for a swift and efficient solution. ...