$route(to, from)


https://www.jianshu.com/p/fa0b5d919615

vue-router中$route 和 $router

1. $route對象

 
$route.png

1.1 $route 表示(當前路由信息對象)

表示當前激活的路由的狀態信息,包含了當前 URL 解析得到的信息,還有 URL 匹配到的 route records(路由記錄)。
路由信息對象:即$router會被注入每個組件中,可以利用它進行一些信息的獲取。

**1.$route.path**
      字符串,對應當前路由的路徑,總是解析為絕對路徑,如 "/foo/bar"**2.$route.params**
      一個 key/value 對象,包含了 動態片段 和 全匹配片段,
      如果沒有路由參數,就是一個空對象。
**3.$route.query**
      一個 key/value 對象,表示 URL 查詢參數。
      例如,對於路徑 /foo?user=1,則有 $route.query.user == 1,
      如果沒有查詢參數,則是個空對象。
**4.$route.hash**
      當前路由的 hash 值 (不帶 #) ,如果沒有 hash 值,則為空字符串。錨點
**5.$route.fullPath**
      完成解析后的 URL,包含查詢參數和 hash 的完整路徑。
**6.$route.matched**
      數組,包含當前匹配的路徑中所包含的所有片段所對應的配置參數對象。
**7.$route.name    當前路徑名字**
**8.$route.meta  路由元信息

 

1.2 route object 出現在多個地方:

(1)在組件內,即 this.$route
(2)在 $route 觀察者回調內 router.match(location) 的返回值
(3)導航守衛的參數:


router.beforeEach((to, from, next) => {
  // to 和 from 都是 路由信息對象
})
watch: {
  $route(to, from) {
     // to 和 from 都是 路由信息對象
  }
}

 

2. $router對象

 
$router.png

全局的路由實例,是router構造方法的實例。
在 Vue 實例內部,你可以通過 $router 訪問路由實例

const router = new Router({
  routes: [
    {
      path: "/",
      name: "首頁",
      redirect: '/home'
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    { path: '*', component: NotFoundComponent }
  ],
  linkActiveClass: "active-router",
  linkExactActiveClass: "exact-router"
})

 

2.1 全局掛載路由實例

// 全局注冊的路由
Vue.use(VueRouter)

2.2 路由實例方法push

// 字符串
      this.$router.push('home')
// 對象
      this.$router.push({ path: 'home' })
// 命名的路由
      this.$router.push({ name: 'user', params: { userId: 123 }})
// 帶查詢參數,變成 /register?plan=123
      this.$router.push({ path: 'register', query: { plan: '123' }})
push方法其實和<router-link :to="...">是等同的。

 

注意:push方法的跳轉會向 history 棧添加一個新的記錄,當我們點擊瀏覽器的返回按鈕時可以看到之前的頁面。

2.2 路由實例方法go

// 頁面路由跳轉 前進或者后退
this.$router.go(-1) // 后退

 

2.3 路由實例方法replace

//push方法會向 history 棧添加一個新的記錄,而replace方法是替換當前的頁面,
不會向 history 棧添加一個新的記錄
<router-link to="/05" replace>05</router-link>

// 一般使用replace來做404頁面
this.$router.replace('/')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM