vue路由的钩子函数和跳转

首页可以控制导航跳转,beforeEach,afterEach等,一般用于页面title的修改。一些需要登录才能调整页面的重定向功能。

  • beforeEach主要有3个参数to,from,next。

  • to:route即将进入的目标路由对象。

  • from:route当前导航正要离开的路由。

  • next:function一定要调用该方法resolve这个钩子。执行效果依赖next方法的调用参数。可以控制网页的跳转。

跳转其他页面

<router-link  :to="{path: 'yourPath', params: { name: 'name', dataObj: data},query: {name: 'name', dataObj: data}}"></router-link>


1. path -> 是要跳转的路由路径,也可以是路由文件里面配置的 name 值,两者都可以进行路由导航
2. params -> 是要传送的参数,参数可以直接key:value形式传递
3. query -> 是通过 url 来传递参数的同样是key:value形式传递

// 2,3两点皆可传递


<template>
  <button @click="sendParams">传值</button>
</template>
<script>
export default {
  name: '',
  data () {
    return {
      msg: 'test message'
    }
  },
methods: {
  sendParams () {
    this.$router.push({
      path: 'yourPath',
      name: '要跳转的路径的 name,在 router 文件夹下的 index.js 文件内找',
      params: {
      name: 'name',
      dataObj: this.msg
      }
    })
  }
},

}
</script>
<style scoped></style>


<template>
  <h3>msg</h3>
</template>
<script>
  export default {
    name: '',
    data () {
      return {
        msg: ''
      }
    },
methods: {
  getParams () {
    // 取到路由带过来的参数
    let routerParams = this.$route.params.dataobj
    // 将数据放在当前组件的数据内
    this.msg = routerParams
  }
},
watch: {
  // 监测路由变化,只要变化了就调用获取路由参数方法将数据存储本组件即可
  '$route': 'getParams'
  }
}
</script>
<style scoped></style>

$route和$router的区别

  $route是“路由信息对象”,包括path,params,hash,query,fullPath,matched,name等路由信息参数。而$router是“路由实例”对象包括了路由的跳转方法,钩子函数等。

猜你喜欢

转载自www.cnblogs.com/tongshuangxiong/p/9668164.html