Vue-Router 的使用
- 在 vue2 项目中,选择使用 vue-router
- 项目目录中会有 router 文件夹,/router/index.js 中配置路由
避免因路由重复报错
import Vue from 'vue'
import Router from 'vue-router'
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)
复制代码
路由配置
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/pages/Home'
import MapTest from '@/pages/Map'
import One from '@/pages/one'
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home,
children:[
{
path: '/map',
name: 'MapTest',
component: MapTest
},
{
path: '/one',
name: 'One',
component: One
}
]
}
]
})
复制代码
路由跳转
1.使用 router-link 路由跳转
<router-link to="/map">router-link路由跳转</router-link>
复制代码
2.使用$router.push 路由跳转
this.$router.push({ name: '需要跳转的路由name'});
复制代码
加载/map 路由下的默认组件
this.$router.push({ path: '/map' })
复制代码
3.路由跳转传参
使用 name 跳转,使用 params 传参
this.$router.push({ name: '路由name', params: { search: value } })
复制代码
获取路由参数
this.$route.params.search
复制代码
使用 name 跳转,使用 query 传参
此方法传递参数,参数会出现在 url 地址中
this.$router.push({name:'路由name',query:{search:value}})
复制代码
获取路由参数
this.$route.query.search
复制代码
使用 path 跳转,在 url 中拼接参数
路由配置
{
path: 'myadmexp/details/:id'
}
复制代码
路由跳转传参
this.$router.push({ path: '路由url'+id})
复制代码
获取路由参数
this.$route.params.id
复制代码
4.使用 router-view 展示路由对应组件
<router-view></router-view>
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END