vue学习笔记 路由基础
一、前面我们提到过单页面富应用阶段,那就要依靠我们的前端路由
vue-router
二、配置安装路由
1、当我们在项目中下载好相关的路由插件后(vue-router)我们就可以使用它了
2、在router文件夹下的index.js中学相关的路由配置代码
//首先导入路由 import VueRouter from 'vue-router' import Vue from 'vue'
3.这里我们同时还要导入vue,使用vue.use安装插件到当前vue程序
//第一步,通过vue.use安装插件 Vue.use(VueRouter)
4、现在创建路由对象,在路由对象中对路由进行相关配置,这里一个path对应一个组件 值得一提的是一般路由的path有“/”
而嵌套路由中不能有‘/’ 嵌套路由在children数组中进行设置,这里的组件都需要import相关的组件
const Home = () =>
import ('../components/Home.vue')
const User = () =>
import ('../components/User.vue')
const About = () =>
import ('../components/About.vue')
const HomeNews = () =>
import ('../components/HomeNews.vue')
const HomeMessage = () =>
import ('../components/HomeMessage.vue')
//创建VueRouter对象
const routes = [
//创建路由组件
{
path: '',
redirect: '/home' //rediret重定向 这里是设置默认情况下的显示页面
},
{
path: '/home',
component: Home,
children: [ //路由的嵌套使用
{
path: '',
redirect: 'news'
},
{
path: 'news', //这里不能加/
component: HomeNews
},
{
path: 'message', //这里不能加/
component: HomeMessage
}
]
},
{
path: '/about',
component: About
},
{
path: '/user/:userId',
component: User
}
]
5、在配置好path和组件的映射关系后,我们就可以根据上面我们配置的路由创建一个路由了
const router = new VueRouter({
routes,
mode: 'history', //默认配置为哈希模式用mode可以指定路由模式
LinkActiveClass: 'active' //处理活跃时候的类名可以在这里改 还可以通过在div中用active-class单个修改
})
6、最后导出,然后在vue的入口文件中挂在路由
router文件夹下的index.js中
export default router
根目录下的main.js中
new Vue({
el: '#app',
router, //挂在路由
render: h => h(App)
})
7、在vue中渲染路由
我们一般使用router-link来渲染路由
<router-link to='/home' tag="button" replace>首页</router-link>
<!-- tag用来指定超链接的形式 replace替代进栈 router-link-active可以用来绑定js事件 -->
<router-link to='/about'>关于</router-link>
<!-- router-link是vue中注册的全局组件 -->
<router-link v-bind:to="'/user/'+userId">用户</router-link>
<router-view></router-view>
<!-- 这个组件告诉我们渲染到哪里 -->
当然你也可以用button啊或者其他的来渲染路由组件,但这需要用method绑定事件
<button @click="homeClick">首页</button>
<button @click="aboutClick">关于</button>
methods: {
//在使用路由之后会有一个全局属性$router
homeClick(){
this.$router.push('/home')
//或者 this.$router.replace('/home')//注意replace和push的区别
},
aboutClick(){
this.$router.push('/about')
}
},
这里我要说一下$router和$route的区别,前者是我们再创建vue-router(总的路由)对象时候会有一个全局的¥router对象
后者是当前正在活跃的路由的对象
浙公网安备 33010602011771号