一、編程式導航
編程式導航就是使用js實現頁面的跳轉,而不是直接在<router-link>中實現跳轉。
1.1 實現編程式導航
實現編程式導航在js中使用this.$router.push(location, onComplete?, onAbort?
)。其中第一個參數就是需要跳轉的頁面的路徑,使用在路由中已經配置好的路徑。可以有以下幾種方式實現跳轉。
// 字符串 //{ path: '/home', component: Home } 路由中已配置home this.$router.push('home') // 對象 //{ path: '/home', component: Home } 路由中已配置home this.$router.push({ path: 'home' }) // 命名的路由 //{ path: '/user/:userId', component: User , name: 'user'} 路由中已配置user,並且路由命名為user. this.$router.push({ name: 'user', params: { userId: '123' }}) //{ path: '/register', component: Register } 路由中已配置register// 帶查詢參數,變成 /register?plan=private this.$router.push({ path: 'register', query: { plan: 'private' }}) //使用get傳值的方式實現編程式動態路由
注意:如果提供了 path
,params
會被忽略,上述例子中的 query
並不屬於這種情況。取而代之的是下面例子的做法,你需要提供路由的 name
或手寫完整的帶有參數的 path
:
const userId = '123' this.$router.push({ name: 'user', params: { userId }}) // -> /user/123 router.push({ path: `/user/${userId}` }) // -> /user/123 //注意此處不是單引號 ' ,而是 `(鍵盤左上角的~鍵).使用 ${varName} 來實現動態傳值
// 這里的 params 不生效
this.$router.push({ path: '/user', params: { userId }}) // -> /user
1.2 使用上面列舉的方式
配置的路由:
//2.定義路由 const routes = [ { path: '/home', component: Home }, { path: '/news', component: News }, { path: '/newsdetail/:index', component: NewsDetail, name: 'detail'}, { path: '/product', component: Product }, { path: '*', redirect: '/home' } //表示沒有匹配到是默認重定向到home組件 ]
實現js跳轉的頁面:<template>
<div> <div>這是home組件</div> <ul> <li v-for="(msg, index) in products" :key="index"> <router-link :to="'/product?index=' + index">{{msg}}</router-link> </li> </ul> <button @click="toNewsPage()">到新聞頁</button> <button @click="toNewsDetail()">動態路由跳到新聞詳情</button> <button @click="toNewsDetail2()">動態路由跳到新聞詳情的第二種編程時導航寫法</button> <button @click="toProduct()">get傳值的方式跳轉到product頁面</button> </div> </template> <script> export default { data() { return { products: [ "這是第一個產品", "這是第二個產品", "這是第三個產品" ] } }, methods: { toNewsPage() { this.$router.push({path: 'news'}) }, toNewsDetail() { this.$router.push({name: 'detail', params: {index: 1}}) }, toNewsDetail2() { let index = 1 this.$router.push({path: `/newsdetail/${index}`}) }, toProduct() { this.$router.push({path: 'product', query: {index: 1}}) } } } </script>