Navigating in Vue.js with the back button

I have already implemented a Vue.js Routing example application found on GitHub. You can check it out here:

https://github.com/chrisvfritz/vue-2.0-simple-routing-example

In my src/main.js, I am managing a lot of data values.

const app = new Vue({
  el: '#app',
  data: {
    currentRoute: window.location.pathname,
    token : "",
    errorMessage : '', and more...
  },

Now, using socket.io, I set the token to "sdawdda2d2ada2ad22ad"

Upon starting the application, the current route is equal to "/", which means the first page gets loaded from src/routes.js.

'/': 'Home',
'/about': 'About'

When navigating to /about (url: localhost:8080/about), everything works as expected, but the token and error message become empty because the app gets created again.

To change the page without losing the token value, I can use:

this.currentRoute = "/about"       (url: localhost:8080)

This method works well, but the URL doesn't change, so I can't utilize the back button in the browser. How can I segregate my Vue app so that I don't lose the token value when navigating to /about?

Answer №1

If you want to navigate backwards, you can use something like this.$router.go(-1) or vm.$router.go(-1). To move forward, try this.$router.go(1). For more information on navigation, please click here.

Answer №2

easy method

<template lang="html">
  <div>   
    <button @click="returnBack">
      Return
    </button>
  </div>
</template>
<script>
  export default {
    methods: {
      returnBack() {
        this.$router.back()
      }
    }
  }
</script>

Answer №3

When transitioning from the Home section to the About section, it is important to utilize the <router-link> element for navigation.

To move from the home page to the about page, you can accomplish this by using the following code:

<router-link to="/about">Go to my About Page</router-link>

This code generates a standard html anchor tag <a> with the correct path. Clicking on it will direct you to the about component without needing to reload the entire webpage (along with any app scripts) from the server.

When only the route component changes, your other Vue parameters such as tokens within the Vue instance will remain intact.

For additional information, refer to the vue-router documentation available at: http://router.vuejs.org/en/essentials/getting-started.html

Make sure to include a placeholder for routes in your main application like so:

<router-view></router-view>
. The Home and About components will be rendered within this router-view when switching between routes.

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

The dictionary of parameters has an empty entry for the 'wantedids' parameter, which is of a non-nullable type 'System.Int32', in the 'System.Web.Mvc.JsonResult' method

The console is showing me an error stating that the parameters dictionary contains a null entry for parameter wantedids. I am trying to pass checked boxes to my controller using an array, so only the admin can check all boxes of tips for a specific user. T ...

Issues with clickable links within a table cell

I am facing an issue with a table where rows <tr> are generated dynamically by a PHP loop. I have transformed the entire row into a link, but the problem arises when there is an <input type="checkbox"> within the row. Whenever I check the check ...

Updating Angular JS views in real-time using database changes

I am currently in the process of building a social networking application using AngularJS. I have come across an issue regarding data binding. In my app, there is a timeline div where all the recent posts are displayed, along with a status updater at the t ...

Using AJAX to invoke a REST service endpoint

I'm currently implementing a REST service call using AJAX. $(document).ready(function () { var xmml = getXmlLoginRequest(); var wsdlURL = getWSDL('search'); $.ajax({ type: "POST", url: wsdlURL ...

Create a collection of objects within Vue

I have been using Objects in Arrays successfully to read data, but I am having trouble initializing them. I require more variables within articleList than just the number, so a normal array won't suffice. Below is what has been working: data(){ ...

Ways to display multiple select options based on the user's selection of multiple choices and ensure they remain hidden and reset when deselected with the use of

There is a select options field that contains languages, where the user can choose multiple language options or just one. When the user selects a language, a new select option should appear for them to choose their proficiency level in that language. If t ...

Retrieve the data from a specific row of a RadGrid on the client side

Hi everyone, I've been struggling with this issue and would appreciate any help or advice you can offer. I've spent the last day and a half trying to figure it out! I'm working on a module for a DotNetNuke portal where I need to populate a ...

Firefox causing jQuery ui datepicker malfunction

My datepicker isn't functioning properly in Firefox browser <div class="input-append datepicker"> <?php if($_REQUEST["date"]){ ?> <input id="filter-date" size="16" type="date" value="<?php echo $_REQU ...

When implementing jQuery for scrolling on a website, touch gestures may become unresponsive on Safari for iOS devices

While developing a custom website with Angular, I encountered an issue specifically with Safari on iOS. The website is a single-page app with multiple menu sections that trigger a scroll animation when selected using jQuery. Everything was working smoothly ...

Assistance needed with the usage of static and dynamic ArrowHelper in Three.js

I am facing an issue with two different code snippets for drawing a vector along a direction defined by the directionVectorLocal vector. The first snippet is as follows: var transportedVector = { coordLocal, arrowHelper, directionVectorLocal, ...

Unpack an array with entries and an iterator

I am working with an array of objects, each containing the same properties. My goal is to create a function that will return an array of arrays, where each inner array holds values based on the property names of the objects. Here is an example input: inp ...

Can a 1D array be utilized to create a 2D grid in React?

I needed to display a one-dimensional array in a 2D grid format with 3 rows and 3 columns. The array itself contains numbers from 1 to 9. const array = Array.from({ length: 9 }, (_, i) => i + 1); In my React component, I have it rendering as a series o ...

Error when using the vue-masonry package in laramix

I am currently working on a Laravel 5.4 project. I have encountered an issue with the vue-masonry package (https://github.com/shershen08/vue-masonry) showing the following error: [Vue warn]: Failed to resolve directive: masonry [Vue warn]: Failed to res ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

Running JavaScript within Objective-C in a Cordova plugin

I'm working with cordova version 6.5.0 and I'm trying to develop a plugin that can execute some javascript code. I've read on various forums that I can use stringByEvaluatingJavascriptFromString method in my webview, but it seems like it&ap ...

Can one iterate over a JavaScript object using forEach() even if the keys are undefined?

During a code review, I came across the following code: var a = { ... }; // an object filled with key-value pairs for (var key in a) { if (!angular.isUndefined(key)) { do.stuff(); } } I am questioning whether key can ever be undefined or ...

establish an online repository with a data storage system

As a beginner in web development, my goal is to design a website with a database that can house all archive files. I want users to have the ability to delete existing files and upload new ones directly from the web page. Utilizing HTML, CSS, and JavaScrip ...

Any tips for avoiding a new line when generating html attribute values to prevent my json string from breaking?

When working with JSON string values in button element attributes, I have encountered an issue where a single quote causes the value to break and create newlines. For example: var $json = JSON.stringify('{"Long_text":"This is \'my json stri ...

Error: Mongoose save() method is undefined

Within my app.js file, I am requiring my model as follows: var User = require('./models/user'); app.post('/user/add', function(req,res,next){ var newUser = new User(); newUser.add(req.body.name, function(response){ res.json(res ...

Trigger a JavaScript function upon the creation of a new tag

I'm currently developing a plugin for a website that involves generating table rows and injecting them into an existing table on the site. These table rows need to be created when a button is pressed, but unfortunately, I don't have direct acces ...