1. 程式人生 > 其它 >Vue實現路由跳轉的幾種方式

Vue實現路由跳轉的幾種方式

1.this. \(router.push( ) 跳轉到指定的URL,在history棧中新增一個記錄,點選後退會返回上一個頁面。 `1. 不帶引數 // 字串 this.\)router.push('/home')
this.\(router.push('/home/first') // 物件 this.\)router.push({path:'/home'})
this.\(router.push({ path: '/home/first' }) // 命名的路由 this.\)router.push({name:'home'})
2. query傳參
this.\(router.push({name:'home',query: {id:'1'}}) this.\)

router.push({path:'/home',query: {id:'1'}})
// html 取參 \(route.query.id // script 取參 this.\)route.query.id
3. params傳參
this.$router.push({name:'home',params: {id:'1'}})
// 只能用 name
// 路由配置 path: "/home/:id" 或者 path: "/home:id" ,
// 不配置path ,第一次可請求,重新整理頁面id會消失
// 配置path,重新整理頁面id會保留
// html 取參 \(route.params.id // script 取參 this.\)
route.params.id
4. query和params區別
query類似 get, 跳轉之後頁面 url後面會拼接引數,類似?id=1, 非重要性的可以這樣傳,
密碼之類還是用params重新整理頁面id還在
params類似 post, 跳轉之後頁面 url後面不會拼接引數 , 但是重新整理頁面id 會消失`
2.this. $router.replace( )
用法同上,但是跳轉到指定的url,不會向history裡面新增新的記錄,點選返回,會跳轉到上上一個頁面,上一個記錄是不存在的。

3.router-link
瀏覽器在解析時,將它解析成一個類似於a標籤。
`基本用法

  • 點選跳轉
  • 1. 不帶引數 //name,path都行, 建議用name // 注意:router-link中連結如果是'/'開始就是從根路由開始,如果開始不帶'/',則從當前路由開始。 2. 帶引數 // params傳引數 (類似post) // 路由配置 path: "/home/:id" 或者 path: "/home:id" // 不配置path ,第一次可請求,重新整理頁面id會消失 // 配置path,重新整理頁面id會保留 // html 取參 $route.params.id // script 取參 this.$route.params.id // query傳引數 (類似get,url後面會顯示引數) // 路由可不配置 // html 取參 $route.query.id // script 取參 this.$route.query.id` 4.this. $router.go(n) 相對於當前頁面向前或向後跳轉多少個頁面,類似 window.history.go(n)。n可為正數可為負數。正數返回上一個頁面。 `this. $router.go(1) //前進一步 相當於history.forward()

    this. $router.go(-1) //後退一步 相當於history.back()

    this. $router.go(10)`