vue跳转网页的两种方式

网页跳转的两种方式

使用a标签()方式跳转




  
  
  
  Document
  
  


  
登录 注册

使用window.location.href方式




  
  
  
  Document
  
  


  
去注册组件

https://router.vuejs.org/guide/essentials/navigation.html

vue跳转网页的两种方式_第1张图片

  • 一定要区分this. r o u t e 和 t h i s . route和this. routethis.router这两个对象
    • this.$route是所有路由的参数对象,params和query都属于它
    • this.$router是路由的导航对象,用它可以方便的使用JS代码,实现路由的前进后退跳转到新的URL地址

↓↓上面网站扒下来的看着方便

程序化导航

除了用于为声明性导航创建锚标签之外,我们还可以使用路由器的实例方法以编程方式执行此操作。

router.push(location, onComplete?, onAbort?)

注意:在Vue实例内部,您可以访问路由器实例 r o u t e r 。 你 可 以 这 样 打 电 话 t h i s . router。你可以这样打电话this. routerthis.router.push。

要导航到其他URL,请使用router.push。此方法将新条目推送到历史堆栈中,因此当用户单击浏览器后退按钮时,它们将被带到先前的URL。

当您单击a时,这是内部调用的方法,因此单击相当于调用router.push(...)

陈述 编程
router.push(...)

参数可以是字符串路径或位置描述符对象。例子:

// literal string path
router.push('home')

// object
router.push({ path: 'home' })

// named route
router.push({ name: 'user', params: { userId: '123' } })

// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' } })

注意params如果path提供了a,则会被忽略,但不是这种情况query,如上例所示。相反,您需要提供name路由或path使用任何参数手动指定整个:

const userId = '123'
router.push({ name: 'user', params: { userId } }) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// This will NOT work
router.push({ path: '/user', params: { userId } }) // -> /user

相同的规则适用于组件的to属性router-link

在2.2.0+,可选地提供onCompleteonAbort回调router.pushrouter.replace作为第二和第三参数。导航成功完成(在解析所有异步挂钩之后)或中止(导航到同一路线,或在当前导航完成之前到不同路线)时,将调用这些回调。

**注意:**如果目标与当前路由相同且只有params正在更改(例如,从一个配置文件转到另一个配置文件/users/1- > /users/2),则必须使用beforeRouteUpdate以对更改做出反应(例如,获取用户信息)。

router.replace(location, onComplete?, onAbort?)

它的作用就像router.push,唯一的区别是它导航时没有按下新的历史记录条目,顾名思义 - 它取代了当前的条目。

陈述 编程
router.replace(...)

router.go(n)

此方法采用单个整数作为参数,指示在历史堆栈中前进或后退的步数,类似于window.history.go(n)

例子

// go forward by one record, the same as history.forward()
router.go(1)

// go back by one record, the same as history.back()
router.go(-1)

// go forward by 3 records
router.go(3)

// fails silently if there aren't that many records.
router.go(-100)
router.go(100)

#历史操纵

您可能已经注意到router.pushrouter.replace并且router.go是同行window.history.pushStatewindow.history.replaceState而且window.history.go,和他们做模仿window.history的API。

因此,如果您已熟悉浏览器历史记录API,则使用Vue Router可以非常轻松地操作历史记录。

值得一提的是,Vue的路由器导航方法(pushreplacego)的所有路由器模式一致地工作(historyhashabstract)。

你可能感兴趣的:(vue跳转网页的两种方式)