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

Switching Symbols with JQuery

Hello, I am brand new to utilizing javascript and I'm currently experimenting with the toggle function. My goal is to create show/hide functionality while also toggling arrow icons. Specifically, I want a right arrow next to the link "More -->" and wh ...

Puppeteer is unable to detect the node.js handlebars helpers

I'm utilizing puppeteer in NodeJs to generate a PDF file. I use handlebars to render the template and pass variables during compilation for handlebars to access them. Here is the current code snippet: const browser = await puppeteer.launch({ he ...

Access the system by logging in with a stored Google account

I have experience integrating "Login via Google account" on various websites. However, some sites like Zomato always display the option to login via Google as soon as you open them. They even show a list of Google accounts that I have previously logged i ...

Top method for changing an array in javascript

I'm in the process of building a react application, and I've received the following array from an API call. var arrayLike ={ "2020-W1": [ { "type": "TAX_REFUND_IN_INT", &q ...

After cloning the variable from props, the Vue 3 Composition API variable becomes undefined

I have a main component containing code and tables, including a modal that is displayed based on a boolean value. The main component features the following modal: <ConfirmPaymentModal ref="confirmPaymentModal" :invoice="markAsPa ...

Is there an issue with MVC5 in passing JSON data to Controller using Ajax?

I am working on implementing duplication checking in my MVC5/EF Code-First application. In the Asset View's Create() method, I use JavaScript to show/hide textboxes for adding a new location_dept/location_room: <div class="form-group"> ...

Displaying a Facebook iframe on the left side of the page

I'm struggling with positioning the Facebook iframe embed to sit on the left of the text. I want it to be aligned with the left margin, but also have the text flow beside it from the same height. Can anyone offer some guidance on how to achieve this u ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete. For reference, attached is an image showcasing the i ...

Why is the promise not returning an integer value, but instead returning undefined?

My validation process includes checking the integrity of the down streaming data to the server and verifying its existence in the database. The code snippet from model.js: const mongoose = require('mongoose'); const User = new mongoose.Schema({ ...

Encountering a 500 Internal Server Error while attempting to upload to an AWS S3 bucket using Nuxt

I am facing an issue while attempting to upload a file to AWS S3 using aws-sdk v3 within a Vue Component of a Nuxt app. Here is the process I follow for the upload: <script> export default { ... methods: { onSubmit(event) { event.preventDefault( ...

Error encountered when attempting to load files from the same domain due to CORS restrictions

I'm currently developing a website at and I am trying to load the content of an HTML file into an element. I have specified the element as $('.about-us-first-col') and I am loading the content using the code: $('.about-us-first-col&apo ...

Having trouble with submitting the second stage of a multi-step form through Ajax technology

I'm currently tackling a multi-step form project using JavaScript, specifically focusing on submitting the second step of the form via Ajax. I've taken the initiative to create a distinct JavaScript file titled ajaxRequest.js to manage the Ajax r ...

The ultimate guide to handling arrays in Vue: tackling the v-model dilemma

Just getting started with Vue and I've been attempting to modify an array of strings using the v-model property. I put together a small JSFiddle where I'm encountering issues with editing the array. An error message appears suggesting that I shou ...

Activate the zoom feature in jquery mobile

I am looking to implement the standard zooming effect in jquery mobile for my iOS iPhone app using jqm 1.3.2. After attempting the following: <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-s ...

how to execute Vue-Js method just one time

Is there a way to add a random number (ranging from 0 to the price of an item) to one of the data properties in Vue.js, but only once when the page is initially loaded? I am unable to use mounted and computed because I need to pass a parameter to the funct ...

What is the most effective method for testing event emitters?

Imagine I have a basic component structured like this: @Component({ selector: 'my-test', template: '<div></div>' }) export class test { @Output selected: EventEmitter<string> = new EventEmitter<string>() ...

Can someone explain why the console.log(items) command seems to be executing twice

Item.find() .then(function (items) { if (items.length === 0) { Item.insertMany(defaultItems) .then(function () { console.log("Successfully Saved"); }) .catch(function (err) { console.l ...

What is the most effective method for storing multiple data points in an array?

I have developed the following script: let data = [ {day: 1, time: '08:00', note: 'madrid'}, {day: 2, time: '08:00', note: 'barcelona'}, {day: 3, time: '10:00', note: 'juve ...