保持Vue状态

时间:2018-04-21 23:05:51

标签: vue.js vuejs2 vue-router

有没有办法保持vue的状态,以便在导航回来时显示?

示例:

1)我在页面A上搜索某些内容,项目已加载,我向下滚动并从列表中选择项目34。

2)现在,页面B打开,包含有关该项目的信息。我点击后退,但结束于空的页面A.

我想要的是搜索结果,理想情况是我离开那个vue时的滚动位置。

这是否可以在vue2中开箱即用,还是我必须自己编写所有这些代码?

1 个答案:

答案 0 :(得分:1)

  

所以你想以某种方式vuejs记住scrollPosition。因为vue一直很简单。

滚动行为可以由Vue-Router管理。我将向您展示一个示例。

具有2个滚动位置的页面组件

<template>
  <div>
      <div id="data1" style="height:700px;background:blue">
        First scroll position
      </div>

      <div id="data2" style="height:700px;background:yellow">
        Second scroll position
      </div>
  </div>
</template>

导航到页面组件的组件

<template>
  <div>
    <router-link 
    tag="button"
    :to="link"
    >
    Navigate to Page in scroll Position 2
    </router-link>
  </div>
</template>
<script>
    export default {
    data: () => ({
      link: {
        name: 'Page',
        hash: '#data2' //<= important,this adds the #data2 in url
      }    
    })
  }
</script>

现在您的路线文件必须如下所示:

import Vue from 'vue'
import Router from 'vue-router'
import Page from '@/components/Page.vue'
import NavigationButton from '@/components/NavigationButton.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/Page',
      name: 'Page',
      component: Page,
    },
    {
      path: '/',
      name: 'NavigationButton',
      component: NavigationButton
    },
    //other routes
  ],
  mode: 'history',
  scrollBehavior(to, from, savedPosition) {
    if(savedPosition){ //when use press back button will go at the position he was on the page
        return savedPosition
    }
    if(to.hash){ //if has a hash positition to go
        return { selector: to.hash } //go to the page in scrolled Position
    }
    return { x:0, y: 0 } //go to the page in scroll = 0 Position
  }  
})

我理解你的问题,但我不确定你的问题。如果我是对的,不要忘了看看关于滚动行为的官方vue-router文档。See here