Vue.js使用后退按钮进行路由

ket*_*tom 6 javascript vue.js vue-router

我已经使用了这个Vue.js路由示例应用程序.

https://github.com/chrisvfritz/vue-2.0-simple-routing-example
Run Code Online (Sandbox Code Playgroud)

src/main.js 我有这么多的数据值.

const app = new Vue({
  el: '#app',
  data: {
    currentRoute: window.location.pathname,
    token : "",
    errorMessage : '', etc...etc..
  },
Run Code Online (Sandbox Code Playgroud)

现在使用socket.io我将令牌设置为 "sdawdda2d2ada2ad22ad"

当应用程序启动时,currentRoute等于"/" 其okey,第一页加载.src/routes.js

'/': 'Home',
'/about': 'About'
Run Code Online (Sandbox Code Playgroud)

当我想检查/ about(url :)时localhost:8080/about,它的工作效果不错,但令牌和errorMessage再次为空,因为应用程序再次创建.

如果我想更改页面而不丢失令牌值,我可以使用:

this.currentRoute = "/about"       (url: localhost:8080)
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但网址没有改变,所以我不能在浏览器中使用后退按钮.如果我不希望在浏览器转到/关闭时丢失令牌值,我如何分离我的Vue应用程序?

非常感谢!

Kar*_*sia 15

你可以做点什么this.$router.go(-1)或者vm.$router.go(-1)继续前进this.$router.go(1),点击这里

  • 如果我按照你的方法,上一页中存在的道具将被设置为空。有没有办法在路由到上一页时保持 prop 值。 (5认同)

小智 5

简单的方法

<template lang="html">
  <div>   
    <button @click="goBack">
      Back
    </button>
  </div>
</template>
<script>
  export default {
    methods: {
      goBack() {
        this.$router.go(-1)
      }
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)


Man*_*ani 3

当您从一条路线移动Home到另About一条路线时,您需要使用<router-link>导航。

从您的home页面,您可以导航到about页面,如下所示:

<router-link to="/about">Go to my About Page</router-link>
Run Code Online (Sandbox Code Playgroud)

这会生成一个常规的 html 锚标记<a>,并且路径设置正确。当您单击它时,它将带您进入该about组件,而不是从服务器刷新整个 html 网页(带有应用程序脚本)。

当仅更改路由组件时,Vue 实例上的所有其他 Vue 参数(例如令牌)将保留。

请查看这里vue-routerhttp://router.vuejs.org/en/essentials/getting-started.html

请记住在主应用程序中为路线设置一个占位符,如下所示:<router-view></router-view>。当您更改路线时,您的Home组件About将被渲染到此中router-view