十六、路由
1.什么是路由
在vue中的路由,能够帮组我们在一个vue组件中实现其他组件的相互切换。也就是说,可以通过路由模块,将制定的组件显示在路由视图上。
2.安装路由模块
- 2-1.
cnpm install vue-router -s //安装路由
cnpm install //更新vue-router所需要的依赖
- 2.2
在src下创建router文件夹。创建index.js文件
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}
]
})
- 2.3
在main.js中导入router
import Vue from 'vue'
import App from './App'
import router from './router' //这个
new Vue({
el: '#app',
router, //这个
components: { App },
template: '<App/>'
})
- 2.4
在App.vue中加入<router-view>标签
<template>
<div id="app">
<router-view><router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
</style>
- 2.5路由跳转
标签式跳转
<router-link to="/路由地址">跳转路径</router-link>
js跳转
this.$router.push({path:url})
- 2.6路由传参
第一种
父页面
<div class="examine" @click="insurance(2)">查看详情</div>
<script>
methods:{
insurance(id) {
//直接调用$router.push 实现携带参数的跳转
this.$router.push({
path: '/particulars/${id}'
})
}
</script>
路由文件配置
{
path: '/particulars/:id', //关键在这里
name: 'particulars',
component: particulars
}
子组件中: 这样来获取参数
this.$route.params.id
第二种
父页面
<div class="examine" @click="insurance(2)">查看详情</div>
<script>
methods:{
insurance(id) {
//直接调用$router.push 实现携带参数的跳转
this.$router.push({
path: 'particulars',
params: {
id: id
}
})
}
</script>
路由文件配置
{
path: '/particulars',
name: 'particulars',
component: particulars
}
子组件中: 这样来获取参数
this.$route.params.id
第三种
父页面
<div class="examine" @click="insurance(2)">查看详情</div>
<script>
methods:{
insurance(id) {
this.$router.push({
path: '/particulars',
query: {
id: id
}
})
}
</script>
路由文件配置
{
path: '/particulars',
name: 'particulars',
component: particulars
}
子组件中: 这样来获取参数
this.$route.query.id
第四种
父页面
<router-link :to="{name:'detail',query:{id:1}}"> xxx </router-link>
路由文件配置
{
path: '/detail',
name: 'detail',
component: particulars
}
子组件取参
this.$route.query.id
2.7子路由
网友评论