安装命令 cnpm i vue-router
安装完毕后:进行配置路由,在src目录下创建router/index.js文件,在index.js文件中进行配置处理:
// 该文件专门用于创建整个应用路由器
import VueRouter from 'vue-router'
// 引入组件
import st from '../components/HelloWorld'
import stc from '../components/Student'
// 创建一个路由器并且需要暴露
export default new VueRouter({
routes:[
{
path:'/student',
component:st
},
{
path:'/class',
component:stc
}
]
})
两个组件:HelloWorld.vue和 Student.vue组件自行创建
在我的main.js入口文件中进行配置这个vue-router 插件以及引入刚写好的index.js路由设置文件
// 该文件是整个项目的入口文件
// 引入vue
import Vue from 'vue'
// 引入app组件,是所有组件的父组件,
import App from './App.vue'
// 关闭vue的生产提示
// 引入vue-router插件
import VueRouter from 'vue-router'
// 引入路由
import router from './router/index'
Vue.config.productionTip = false
// 使用vue-router插件
Vue.use(VueRouter)
// 创建vue实例对象,
new Vue({
// 将app组件放到容器中
render: h => h(App),
router:router
}).$mount('#app')
在我的相应的组件中使用router-link to 以及router-view进行操作
<template>
<div id="app">
<ul>
<li>
<router-link to="/student" active-class="active">学生管理</router-link>
</li>
<li>
<router-link to="/class" active-class="active">课程管理</router-link>
</li>
</ul>
<div id="content">
<!--指定组件的呈现位置-->
<router-view></router-view>
</div>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld'
import Student from './components/Student'
export default {
name: 'App',
components: {
HelloWorld,
Student
}
}
</script>
<style scoped>
*{
padding: 0px;
margin: 0px;
}
ul{
width: 16%;
float: left;
text-align:center;
list-style-type: none;
}
li{
width: 100%;
background-color:burlywood;
}
a{
color:white;
}
#content{
float: left;
width: 84%;
padding: 10px 0px;
background-color: burlywood;
text-align: center;
color: white;
}
.active{
background-color:blue;
width: 100%;
}
</style>
最终效果:
更多推荐
vue-router路由器的基础原理案例,实现页面无刷新切换
发布评论