目录
路由的使用
import Vue from 'vue'
import App from './App' //根文件
import router from './router' //引入路由和模块文件
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
components: { App }, //定义组件
template: '<App/>', //把组件渲染出来
router //注册(定义文件)
})
路由文件的配置(redirect和children)
import Vue from 'vue
import router from 'vue-router' //引入路由模块
import hello from '../component/hello' //引入vue页面模块
...... //还有一些引入页面模块的代码就省略了
Vue.use(router) //使用模块
export default new router({
router:[{
path:'/',
name:'hello',
component:'hello' //使用模块
},{
path:'/hello',
name:'hello',
component:'hello' //
},{
path:'/gonsi',
name:'gonsi',
redirect:{"name":'gn'}, //重定向:每当执行到此处,都会重新指向另外一个页面,这个页面可以是自己的子页面(嵌套路由)
component:gonsi,
children:[ //嵌套路由,在gonsi下面的嵌套子路由
{
path:'gn',
name:'gn', //设置name值,根据name值来重定向
component:gn
},
{
path:'gw',
name:'gw',
component:gw
}
]
},{
path:'/twolist/:type', // 给路由传参 :type 就是要传输的值
name:'twolist',
component:twolist
},{
path:'/detaild/:type/:id',
name:'detaild',
component:detaild
},{
path:'*', //表示上面的页面都没找到就会进入这个页面,一般用于404页面
name:'404',
component:detaild
}]
})
路由的跳转和传参方法
<template>
<div id="app">
//路由的跳转1
<router-link to="/twolist">跳转hello</router-link>
//传参的方法1
<router-link :to="'/twolist/'+'this is params'">跳转hello</router-link>
//传参的方法2
<router-link :to="{'name':'twolist',params:{type:'this is params'}">跳转hello</router-link>
</div>
</template>
<script>
export default{
methods:{
a(){
//路由的跳转2 通过函数进行跳转
//括号内的值是路由配置文件里的path值,也就是你想要跳转到那个模块的path值
this.$router.push('/home');
//传参的方法3
this.$router.push({'name':'twolist',params:{type:'this is params'}})
//这种传参方式基本上可以理解为 ajax 中的 post 请求方式,参数都是不可见的,但是有一个弊端,就是当页面刷新了是获取不到参数值的
//传参的方法4
this.$router.push({'name':'twolist',query:{type:'this is params'}})
//用query来传参,这种方式是可以解决页面刷新参数消失问题的,这种方式可以理解为是 ajax 中的 get 方法,参数是直接在 url 后面添加的,参数是可见的,所以解决页面刷新参数消失问题建议使用此方法来解决;
}
}
}
}
</script>
路由参数接收
通过this.$route
获取参数,注意参数名
props属性
// 路由配置
{
path:'/detail/:id',
name:'detail',
component:Detail,
props:true // 如果props设置为true,$route.params将被设置为组件属性
}
// 路由跳转
this.$router.push({
path:`/detail/${id}`
})
// 详情页获取参数
export default {
props:['id'], // 将路由中传递的参数id解耦到组件的props属性上
mounted(){
console.log("id",this.id);
}
}