什么是路由
1 路由就是一组映射关系 (key - value)
2 key为路径 value可以是fuction也可是component
安装 npm install vue-router@3
vue-router4只能在vue3 使用,vue-router3才能在vue2中
vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起来。
在vue-router单页面应用中,则是路径之间的切换,实际上就是组件的切换
编写router配置项:src/router/index.js该文件专门用于创建整个应用的路由器
import Vue from 'vue' //引入Vue
import Router from 'vue-router' //引入vue-router
import Hello from '@/components/Hello' //引入根目录下的Hello.vue组件
Vue.use(Router) //应用插件
//配置路由,首先对外暴露vue router实例
export default new Router({
routes: [ //配置路由,这里是个数组
{ //每一个链接都是一个对象
path: '/hello', //链接路径
name: 'Hello', //路由名称,方便写对象传参
component: Hello //对应的组件模板
},{
path:'/hi',
component:Hi,
children:[ //子路由,嵌套路由 (通过children配置子路由)
{
path:'/hi1', //此处一定不要写/hi1
component:Hi
},
{
path:'hi2', //此处一定不要写/hi2
component:Hi1
},
]
}
]
})
回到main.js文件引入路由并注册
//引入路由
import router from '@/router';
new Vue({
render: h => h(App),
//注册路由 小写
router,
}).$mount('#app')
再去App.vue文件中
<template>
<div>
<!-- 路由组件出口的地方 -->
<router-view></router-view>
</template>
路由组件通常放在pages文件夹,一般组件放在components文件夹
通过切换‘隐藏’的路由组件,默认是被销毁的,需要的时候再去挂载
每个组件都有自己的$route属性,里面存储自己的路由信息
整个应用只有一个router,可以通过$router属性获取到
$route:一般获取路由信息【路径 query params】
$router:一般进行编程式导航跳转【push/replace】
<button @click = "goSearch">搜索</button>
<script>
export default {
name:'';
methods :{
goSearch(){
this.$router.push('/serch')//搜索页面路径
}
}
}
</script>
路由传参
{
path:"/search/:key" ,//params参数需要占位
component:Search,
name:"search" //给路由命名 对象传参写法
}
<input v-model = "key"></input> //双向绑定获取表单数据
<button @click = "goSearch">搜索</button>
<script>
export default {
name:'';
data(){
return {
key:'' //获取表单数据
}
}
methods:{
//对象传参写法
//点击直接带上params query参数 跳转到search页面
goSearch(){
this.$router.push(
{
name: "search",
params: { key: this.key },
query: { k: this.key.toUpperCase() },
},
})
//
}
</script>
1 传递参数
this.$router.push({name:'路由name',params:{search:value}})
获取参数
this.$route.params.search
2.通过path携带的参数
传递
this.$router.push({ path: '路由url'+id})
获取
this.$route.params.id
注意此方法使用时需在路由path中配置 /:id
{
path: 'myadmexp/details/:id'
}
3.通过query来传递参数,使用此方法传递的参数会出现在url地址中
传递
this.$router.push({ name:'name' ,query:{id:code,id2:code2}});
获取
this.$route.query.id;
this.$route.query.id2;