Vue vue-router

VueRouter对象

redirect重定向

children嵌套

router-link标签

<router-link to="路由地址"> </router-link>

router-view标签

路由占位符

<router-view> </router-view>

案例

	  //组件
      const User = {
        template: '<h1>User 组件</h1>'
      }

      const Register = {
        template: '<h1>Register 组件</h1>'
      }
     
      // 创建路由实例对象
      const router = new VueRouter({
        // 所有的路由规则
        routes: [
          // 路由重定向
          {path:'/',redirect:'/user'},
          //动态路由
          { path: '/user/:id', component: User },
          { path: '/register', component: Register,children:{
          	{path:'/child',component:Child},
          	{path:'/child2',component:Child2}
          } }
        ]
      })

      // 创建 vm 实例对象
      const vm = new Vue({
        // 指定控制的区域
        el: '#app',
        data: {},
        // 挂载路由实例对象
        // router: router
        router
      })

路由传参:动态路由传参

//路由地址
  { path: '/user/:id', component: User },
<router-link to="/login/1"> </router-link>
<router-link to="/login/2"> </router-link>

获取参数

this.$route.params.id

或者使用组件的props接收
路由地址需要开启props

//路由地址
  { path: '/user/:id', component: User, props: true},

然后组件内部声明props属性

props:['id']

路由传参path+query 或 name+params

起始页

<template>
  <div>
	  <router-link to="/home?name=zs">跳转</router-link>
	  <el-button @click="toHome">跳转</el-button>
	  <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'App',
	methods:{
		toHome(){
			this.$router.push('/home?name=zs')
			this.$router.push({
				path:'/home',
				query:{
					name:'zs'
				}
			})
			//接收页created函数:this.$route.query.name
			this.$router.push({
				name:'home',
				params:{
					name:'zs'
				}
			})
			//接收页created函数:this.$route.params.name
		}
	},	
}
</script>

组件页面

<template>
  <div>
    home
  </div>
</template>

<script>
export default {
    data(){
      return{}
    },
    created(){
      console.log(this.$route.query.name);
    }
}
</script>

<style scoped>

</style>

路由守卫 router.beforeEach

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
    // 如果to的地址是登录页,那么直接放行
    if (to.path === '/login') {
        return next();
    }

    // 否则查看有没有token,token为空则强制跳转登录页
    const tokenStr = sessionStorage.getItem('token')
    if (!tokenStr) {
        return next('/Login');
    }
    next();
})

编程式导航 this.$router.push和go

//后退1页
this.$router.go(-1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值