代码之家  ›  专栏  ›  技术社区  ›  dsky

保持Vue状态

  •  0
  • dsky  · 技术社区  · 6 年前

    是否有办法保持vue的状态,以便在返回时显示vue?

    例子:

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

    2) 现在,第B页打开,显示有关该项目的信息。我单击“上一步”,但在空页A上结束。

    我想要的是搜索结果,最好是我离开vue时的滚动位置。

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Roland    6 年前

    因此,您希望以某种方式vuejs记住滚动位置。与往常一样,vue非常简单。

    滚动行为可由Vue路由器管理。我给你举个例子。

    具有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路由器官方文档。 See here