javascript - 如何使用 Vue Router 导航到特定元素的 ID?
问题描述
我有这个数据集:
data() : {
navigation : {
section : {
story : {}
}
},
}
我有三个组件,一个用于navigation
和。section
story
我的组件是这样工作的:
//navigation component
<div v-for="section in navigation.section" :key="section.id">
<p> I am Section {{section.name}} </p>
<section-component :currentSection="section"></section-component>
</div>
在我的部分组件中,我有这个。
//section component
<div v-for="story in currentSection.story" :key="story.id">
<p> I am the Story about {{story.hero}} </p>
<story :content="story"></story>
</div>
最后在我的最后一个组件里面story
//story component
<div>
<p> Here is the story! {{content.story}}</p>
</div>
好的,现在我想做的是,我想做一个可以浏览我的故事的导航(比如一章,或者一本书)
我的导航组件中的示例有:
- Section batman
- Batman story
- Catwoman story
- Bat story
- Wheres robin
- Animal Section
- Leo story
- Dog story
所以我想,当我按下“知更鸟在哪里”时,我的部分组件显示“蝙蝠侠部分”,然后滚动到“知更鸟在哪里”。
我知道你可以使用 Vue.router 来设置命名路由,所以我尝试了这个:
{
path: "/navigation/:sectionName/:StoryNameid",
component: navigation,
children: [
{ path: '', component: section }, children: [
{ path: '', component: story}]]
}
我不知道在哪里给 Vue.router 我的 2 个参数以及如何将它们与我的部分相关联。
如果可能的话,我想使用这样的链接。
www.mystorys.com/navigation/sectionBatman/wheresRobin
我的显示如下所示:
+------------------+
| Section |
| +--------------+ |
| | Story1 | |
| +--------------+ |
| +--------------+ |
| | Story 2 | |
| | | |
| +--------------+ | -
| +-------------+ |
| | Story 3 | |
| | |
| +-------------+
解决方案
对于显示部分,您可以使用Nested routes。查看链接的文档,它指定了您想要的确切用例。您需要<router-view>
在导航组件中放置一个 vue-router 将自动替换为<section-component>
. 像这样更改路由器路径定义:
{
path: "/navigation/:sectionName",
component: navigation,
children: [
{ path: '', component: section },
],
}
添加一个路由器视图并通过部分名称传递 currentSection 属性:
//navigation component
<div v-for="section in navigation.section" :key="section.id">
<p> I am Section {{section.name}} </p>
</div>
<router-view :currentSection="getSectionByName($route.params.sectionName)"></router-view>
<script>
export default {
methods: {
getSectionByName(sectionName) {
return this.navigation.section.find((section) => section.name === sectionName);
},
},
}
</script>
接下来,要滚动到您的故事,您可以
- 给每个故事组件一个 id,然后将其添加到路由中:
<div v-for="story in currentSection.story" :key="story.id">
<p> I am the Story about {{story.hero}} </p>
<story :id="story.id" :content="story"></story>
</div>
<router-link to="navigation/sectionBatman#wheresRobin">Where's Robin</router-link>
- 使用 vue-router 的滚动行为
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
return {
selector: to.hash,
};
},
});
推荐阅读
- html - 如何在 Bootstrap 4 中将导航栏项目右对齐?
- go - 如何为 idtoken.NewClient 设置超时选项
- c# - 如何使用 .contains() 方法检查我的列表中是否有任何单词
- javascript - 选择选择器未显示所选选项
- excel - vba可见总过滤器
- bash - 双while循环中的Bash反向逻辑
- typescript - Nuxtjs:模块解析失败:意外字符'@'
- ios - 使用通用类型时,类型“FetchAPI”不符合协议“可解码/可编码”
- postgresql - 如何在使用 pyodbc 查询 PostgreSQL 9.5 表的 Python 脚本中修复“类型 tid 的无效输入语法”?
- linux - 如何在 Linux 中自动创建目录结构?