javascript - 如何在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?
解决方案
假设您想将焦点放在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();
}
}
这应该适用于所有情况。
推荐阅读
- python - 是否有区别:“file.readlines()”、“list(file)”和“file.read().splitlines(True)”?
- angular - 项目被删除,但是当您离开页面并返回时,即使它不在邮递员中,也会再次放置该项目
- android - 如何从适配器外部访问 Recyclerview.ViewHolder 参数?
- android - instabug 文本对齐错误
- hyperledger-composer - 如何在 hyperledger-composer 事务处理器中定义 BusinessNetworkConnection?
- mysql - 安装 file_key_management
- android - 带有动画的自定义圆形切换按钮
- java - 无法在 AWS-Lambda 项目中导入“com.amazonaws.services.lambda.runtime.events.SQSEvent”
- javascript - 过滤/排序数组
- android - 即使安装了 USB 驱动程序,我也无法找到我的设备