vue 左右联动 + 锚点
时间: 2023-09-06 13:09:15 浏览: 30
Vue 左右联动可以通过使用 `watch` 监听左侧菜单的选择,然后根据选择的不同来更新右侧的内容。具体实现可以参考以下代码:
左侧菜单:
```
<template>
<div>
<ul>
<li v-for="(item, index) in menuList" :key="index" @click="selectMenu(index)">
{{ item.title }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
menuList: [
{
title: '菜单1',
content: '菜单1的内容'
},
{
title: '菜单2',
content: '菜单2的内容'
},
{
title: '菜单3',
content: '菜单3的内容'
}
],
activeIndex: 0
}
},
methods: {
selectMenu(index) {
this.activeIndex = index
}
},
watch: {
activeIndex(val) {
// 触发右侧内容的更新
this.$emit('select', val)
}
}
}
</script>
```
右侧内容:
```
<template>
<div>
<div v-for="(item, index) in contentList" :key="index">
<h3 id="title">{{ item.title }}</h3>
<p>{{ item.content }}</p>
</div>
</div>
</template>
<script>
export default {
props: {
menuList: {
type: Array,
default: () => []
}
},
data() {
return {
contentList: []
}
},
mounted() {
// 初始化右侧内容
this.contentList = this.menuList
},
methods: {
updateContent(index) {
this.contentList = [this.menuList[index]]
}
},
created() {
this.$on('select', this.updateContent)
}
}
</script>
```
这样,左侧菜单选择后,右侧内容会更新为相应的内容。
关于锚点,可以使用 `vue-router` 中的 `scrollBehavior` 来实现。具体实现可以参考以下代码:
```
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/menu/:index',
name: 'menu',
component: Menu,
props: true,
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return {
selector: to.hash
}
} else {
return { x: 0, y: 0 }
}
}
}
]
})
```
在左侧菜单中,使用 `router-link` 来跳转到相应的锚点:
```
<router-link :to="{ name: 'menu', params: { index: index }, hash: 'title' }">{{ item.title }}</router-link>
```
这样点击菜单后,会跳转到相应的锚点位置。