🌵vue一级路由如何实现
步骤一:安装插件:npm install vue-router@3.2.0,版本不要太高,容易出问题
步骤二:在main.js文件引入并使用插件
import VueRouter from 'vue-router'
Vue.use(VueRouter)
步骤三:创建一个router文件夹,里面创建一个index.js文件
步骤四:index.js文件里面编写router配置项
//该文件专门用于创建整个应用的路由器
//引入VueRouter
import VueRouter from "vue-router"
// 引入路由组件
import School from '../pages/School'
import Student from '../pages/Student'
// 创建一个路由器
const router = new VueRouter({
//路由器里面包含一堆路由routes,值为数组,每一组路由都是一个配置对象
routes: [{
path: '/school', //匹配路径
component: School //查看路径对应的组件
}, {
path: '/student', //匹配路径
component: Student //查看路径对应的组件
}]
})
//暴露路由器
export default router
步骤五:在main.js文件引入路由器
//引入路由器
import router from './router'
new Vue({
render: h => h(App),
router: router //配置路由
}).$mount('#app')
步骤六:在组件中实现切换效果
<router-link active-class="active" to="/school">School</router-link>
<router-link active-class="active" to="/student">Student</router-link>
<!-- 指定组件的呈现位置 -->
<router-view></router-view>
效果展示:
一级路由最终效果图
🌵vue多级路由如何实现
注意:
- 子组件要展示的内容要写在对应的父组件的里面
- 路由匹配规则也是写在对应父路由规则内,使用children配置项
- 组件内实现切换效果时注意子级路由需带上父级路由
配置路由代码:
routes: [{
path: '/school', //匹配路径
component: School //查看路径对应的组件
},
{
path: '/student', //匹配路径
component: Student, //查看路径对应的组件
children: [{
path: 'boy', //子路由匹配路径,注意不加“/”了
component: Boy //查看路径对应的组件
},
{
path: 'girl', //子路由匹配路径,注意不加“/”了
component: Girl //查看路径对应的组件
},
]
}
]
使用代码:
<div>
<h2>我是Student组件</h2>
<ul>
<!--每次点击都会重新匹配路由,跳转需写完整路径-->
<li><router-link to="/student/boy">boy</router-link></li>
<li><router-link to="/student/girl">girl</router-link></li>
</ul>
<div class="box">
<!-- 放对应组件 -->
<router-view></router-view>
</div>
</div>
效果展示:
多级路由最终效果图
🌵路由的query参数
一、配置路由
{
path: '/student',
component: Student,
children: [{
path: 'boy',
component: Boy,
},
{
path: 'girl',
component: Girl,
children: [{
name: 'xiangqing',
path: 'detail', //query注意路径配置
component: Detail,
}]
},
]
}
二、传递参数
<!-- 跳转并携带query参数,to的字符串写法 -->
<!-- <router-link :to="`/student/girl/detail?id=${n.id}&title=${n.title}`">{{n.title}}</router-link> -->
<!-- 跳转并携带query参数,to的对象写法 -->
<router-link
:to="{
path:'/student/girl/detail',
query:{
id:n.id,
title:n.title
}
}">
{{n.title}}
</router-link>
三、接收参数
$route.query.id
$route.query.title
传参最终效果图
🌵路由的params参数
一、配置路由,声明接收参数,如果传递参数采用的是对象写法,记得配置name属性
{
path: '/student',
component: Student,
children: [{
path: 'boy',
component: Boy,
},
{
path: 'girl',
component: Girl,
children: [{
name: 'xiangqing',
path: 'detail/:id/:title', //使用占位符声明接收params参数
component: Detail,
}]
},
]
}
二、传递参数
<!-- 跳转并携带params参数,to的字符串写法 -->
<router-link :to="`/student/girl/detail/${n.id}/${n.title}`">{{n.title}}</router-link>
<!-- 跳转并携带params参数,to的对象写法 -->
<!-- 特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置! -->
<router-link :to="{
name:'xiangqing',
params:{
id:n.id,
title:n.title
}
}">
{{n.title}}
</router-link>
三、接收参数
$route.params.id
$route.params.title
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/6230.html