用vue写个导航条代码
时间: 2023-03-13 19:16:58 浏览: 81
我可以给你一些参考代码:<template>
<div>
<ul>
<li><router-link to="/">首页</router-link></li>
<li><router-link to="/about">关于我们</router-link></li>
<li><router-link to="/products">产品</router-link></li>
</ul>
</div>
</template>
相关问题
用vue写个顶部导航栏并且点击右边的标题会跑到中间
以下是一个简单的示例代码,实现了一个顶部导航栏,点击右边的标题会跑到中间:
```
<template>
<div class="nav">
<div class="nav-left">
<span class="nav-title">左侧标题</span>
</div>
<div class="nav-center">
<span class="nav-title">{{ currentTitle }}</span>
</div>
<div class="nav-right">
<span class="nav-title" @click="scrollToCenter">右侧标题</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTitle: '中间标题'
}
},
methods: {
scrollToCenter() {
// 获取中间标题的位置
const centerTitle = document.querySelector('.nav-center .nav-title')
const centerTitleRect = centerTitle.getBoundingClientRect()
const centerTitleOffset = centerTitleRect.left + centerTitleRect.width / 2
// 滚动到中间标题的位置
window.scrollTo({
left: centerTitleOffset - window.innerWidth / 2,
behavior: 'smooth'
})
}
}
}
</script>
<style scoped>
.nav {
display: flex;
align-items: center;
justify-content: space-between;
height: 50px;
background-color: #eee;
font-size: 18px;
font-weight: bold;
padding: 0 20px;
}
.nav-title {
cursor: pointer;
}
.nav-center {
flex-grow: 1;
text-align: center;
}
</style>
```
在这个示例中,顶部导航栏被划分为三个部分:左侧、中间和右侧。中间部分显示当前的标题,右侧部分的标题被点击时,页面会滚动到中间标题的位置。
为了实现滚动效果,我们使用了 `window.scrollTo()` 方法,将页面滚动到指定的位置。在这个方法中,我们需要传入一个对象,包含两个属性:`left`(水平滚动距离)和 `behavior`(滚动行为,可以是 "auto"、"smooth" 或 "instant")。
注意,在 `scrollTo()` 方法中计算滚动距离时,我们使用了 `window.innerWidth` 属性,这是窗口的内部宽度,也就是视口的宽度,不包括滚动条的宽度。我们可以用这个属性计算出中间标题的位置和窗口的滚动距离。
vue导航条页面切换
以下是使用Vue实现导航条页面切换的示例代码:
```html
<template>
<div>
<nav>
<ul>
<li :class="{ active: currentIndex === 0 }" @click="changePage(0)">学校新闻</li>
<li :class="{ active: currentIndex === 1 }" @click="changePage(1)">就业新闻</li>
<li :class="{ active: currentIndex === 2 }" @click="changePage(2)">校园活动</li>
</ul>
</nav>
<div v-if="currentIndex === 0">
<h2>学校新闻</h2>
<!-- 学校新闻内容 -->
</div>
<div v-if="currentIndex === 1">
<h2>就业新闻</h2>
<!-- 就业新闻内容 -->
</div>
<div v-if="currentIndex === 2">
<h2>校园活动</h2>
<!-- 校园活动内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0, // 当前选中的页面下标
};
},
methods: {
changePage(index) {
this.currentIndex = index; // 切换页面
},
},
};
</script>
<style>
nav ul li {
display: inline-block;
padding: 10px;
cursor: pointer;
}
nav ul li.active {
background-color: #ccc;
}
</style>
```
在上述代码中,我们使用了一个`currentIndex`变量来表示当前选中的页面下标。通过点击导航条中的不同选项,我们可以调用`changePage`方法来切换页面,并根据`currentIndex`的值来显示对应的内容。同时,我们使用了动态绑定`class`属性来为当前选中的选项添加样式。
阅读全文
相关推荐
















