使用BootstrapVue组件库的navbar组件来构建导航栏。导航栏中包括页面导航,注册,登陆以及发布问题按钮等内容。
安装BootstrapVue
在项目根目录下运行命令 npm install vue bootstrap-vue bootstrap -S
等待安装完成之后,修改src/main.js文件,引入并注册BootstrapVue
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Vue.config.productionTip = false
// Install BootstrapVue
Vue.use(BootstrapVue)
// Optionally install the BootstrapVue icon components plugin
Vue.use(IconsPlugin)
new Vue({
router,
render: h => h(App),
}).$mount('#app')
编写导航组件
编写文件src/components/NavBar.vue
<template>
<div class="navbar-body">
<b-navbar toggleable="sm" type="light" variant="light" fixed="top">
<b-navbar-toggle target="nav-text-collapse"></b-navbar-toggle>
<b-navbar-brand>AntFootQA</b-navbar-brand>
<b-collapse id="nav-list" is-nav>
<b-navbar-nav>
<b-nav-item to="/">最新问题</b-nav-item>
</b-navbar-nav>
</b-collapse>
<b-navbar-nav class="create-question">
<b-button @click="handleCreateQuestion" variant="success"><b-icon-plus></b-icon-plus>提问题</b-button>
</b-navbar-nav>
<b-navbar-nav align="right" v-if="userInfo">
<b-nav-item-dropdown right>
<!-- Using 'button-content' slot -->
<template #button-content>
{{userInfo.name}}
</template>
<b-dropdown-item @click="handleLogout">退出登录</b-dropdown-item>
</b-nav-item-dropdown>
</b-navbar-nav>
<b-navbar-nav align="right" v-else>
<b-nav-item to="/user/register">注册</b-nav-item>
<b-nav-item to="/user/login">登录</b-nav-item>
</b-navbar-nav>
</b-navbar>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'Navbar',
data () {
return {}
},
computed: {
...mapState({
userInfo: state => state.user.userInfo
}),
},
methods: {
handleLogout() {
this.$store.dispatch('Logout').then(() => {
this.$router.push('/')
})
},
handleGetUserInfo() {
this.$store.dispatch('GetInfo')
},
handleCreateQuestion () {
if (!this.userInfo) {
this.$router.push('/user/login')
} else {
this.$router.push('/question/create')
}
}
},
created () {
this.handleGetUserInfo()
}
}
</script>
<style scoped>
.navbar-body {
margin-bottom: 80px;
}
.create-question {
margin-right: 10px;
}
</style>
导航栏组件将会在后边开发的src/layouts/HomeLayout.vue主页布局组件中引入,所以当页面访问到除了注册、登录页面外,会通过引入导航栏,执行这里的created方法,进而获取一次用户信息
created () {
this.handleGetUserInfo()
}