【问题标题】:How to route to specific div in a component in vuejs 2如何在vuejs 2中路由到组件中的特定div
【发布时间】:2018-11-15 16:32:20
【问题描述】:

我的申请路线是

const router = new VueRouter({
mode:'history',
routes:[
    {
        path:'/home',
        name:'home',
        component: Home
    },
    {
        path: '/services',
        name: 'services',
        component: Services
    },
    {
        path:'/blogs',
        name:'blogs',
        component:Blogs
    },
    {
        path:'/pingme',
        name:'pingme',
        component:Pingme
    }
],

})

现在,在服务路线中,我想导航到 Home 组件中存在的路线。如何创建路由器以便在单击服务链接时导航到服务 div?

【问题讨论】:

  • 你的意思是要从 /services 路由路由到 /home 组件中的特定 div 吗?
  • 你的意思是,router link怎么用?
  • 是的 Jayesh Dhandha 完全正确

标签: javascript laravel-5 vue.js vuejs2 vue-router


【解决方案1】:

假设您想将焦点放在 Service 组件中的特定 div 上。

我们将使用查询参数来实现这一点。您还添加了一个专用的 url,它将执行此操作。

这是我的路线:

{
    path: '/services',
    name: 'services',
    component: Services
}

然后在 url localhost:8000/services?show=mydiv 和组件的挂载钩子中执行以下操作:

mounted() {
  // add a id to the div we want to bring in foucs
  // and id and the id is paased the query params
  document.getElementById(this.$route.query.show).scrollIntoView()
}

让我知道它是否适合您。

编辑

另一种实现这项工作的方法是使用观察者和计算属性。

首先为路由中的显示查询参数添加一个计算属性。

computed: {
  show() { return this.$router.query.show }
}

然后添加一个观察者来触发焦点。

watch: {
  show: {
    immediate: true,
    handler(value) { 
      document.getElementById(value).scrollIntoView();
    }
}

这应该适用于所有情况。

【讨论】:

  • 是的,它正在工作。但是新的问题出现了。当我在 pingme 组件中时,我可以移动到主页组件中的服务部分,但是当我在主页组件中并单击服务链接时,没有任何反应。
  • 什么都没有发生,因为它没有被重定向或者 div 没有被聚焦?
  • Div 没有聚焦
  • 我知道了,所以我们可能想要使用观察者。更新我上面的答案。
  • 不,没有用。请如果您分享一些高度赞赏的解决方案
猜你喜欢
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
相关资源
最近更新 更多