首页 > 解决方案 > 如何在vuejs 2中路由到组件中的特定div

问题描述

我的申请路线是

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?

标签: javascriptlaravel-5vue.jsvuejs2vue-router

解决方案


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

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

这是我的路线:

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

然后在 urllocalhost: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();
    }
}

这应该适用于所有情况。


推荐阅读