声明式导航&编程式导航

1.在浏览器中,点击链接实现导航的方式,叫做声明式导航,例如:

普通网页中点击<a>链接、vue项目中点击<router-link>都属于声明式导航

2.在浏览器中,调用API方法实现导航的方式,叫做编程式导航,例如:

普通网页中调用location.href跳转到新页面的方式,属于编程式导航

vue-router中的编程式导航API

1.this.$router.push('hash地址')

跳转到指定hash地址,并增加一条历史记录(可后退)

<button @click="gotoLK">跳转到电影1页面</button>
methods: {
  gotoLK(){
    // 通过编程式导航API,导航跳转到指定的页面(可后退)
    this.$router.push('/movie/1')
  },
  },

 

2.this.$router.replace('hash地址')

跳转到指定的hash地址,并替换掉当前的历史纪录

<button @click="gotoLK2">跳转到电影2页面</button>
methods: {
  gotoLK2(){
      // 通过编程式导航API,导航跳转到指定的页面(不可后退)
      this.$router.replace('/movie/2')
  }
  },

3.this.$router.go(数值n)

可在浏览器历史中前进和后退

  <button @click="goBack1">后退</button>
  <button @click="goBack2">前进</button>
  methods:{
  goBack1(){
    // go(-1)后退一层
    this.$router.go(-1)
    // go(-100)如果后退层数超过上限,则原地不动
  this.$router.go(-100)
  },
  goBack2(){
      this.$router.go(1)
  }
}

$router.go的简化方法

在实际开发中,一般只会前进和后退一层页面,因此vue-router提供了如下两个便捷方法:

1.$router.back()

//在历史记录中,后退到上一个页面

  <button @click="$router.back()">后退</button>

2.$router.forward()

//在历史记录中,后退到下一个页面

  <button @click="$router.forward()">前进</button>

 

posted @ 2021-09-15 23:01  ajaXJson  阅读(254)  评论(0编辑  收藏  举报