【问题标题】:Keeping State of Vue保持 Vue 的状态
【发布时间】:2018-10-02 07:29:10
【问题描述】:

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

例子:

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

2) 现在页面 B 打开,其中包含有关该项目的信息。我点击返回,但在一个空的页面 A 上结束。

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

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

【问题讨论】:

  • 是的,你必须使用 vuex
  • OP 希望在页面导航前后保持状态,而不是通常的状态管理 Vuex 通常是关于。

标签: vue.js vuejs2 vue-router


【解决方案1】:

所以你想以某种方式让 vuejs 记住滚动位置。一如既往地使用 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

【讨论】:

    猜你喜欢
    • 2019-04-16
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 2012-03-09
    相关资源
    最近更新 更多