iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 18
0
Modern Web

Vue菜鳥的自我學習days系列 第 18

18.利用 Router 切換頁面內容

雖然已經完成了商品詳情內容,但電商網頁一般都會以另一個頁面顯示商品內容,現在我們透過 Router 來完成
SPA 頁面切換;
在 main.js 加入 router 的註冊

import Vue from 'vue';
import router from './router';
import ProductApp from './ProductApp';
...
new Vue({
router,
render: h => h(ProductApp),
}).$mount('#app');

接著編輯 router.js 來進行 router 對應設定,我們可以看到在 vue-cli 建立專案後,routes 底下已經有兩種定義方式

export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue'),
},
],
});

第二種定義方式在註解中已經說明,當造訪頁面時才真正建構並讀取該 component 實體

route 物件需要定義三個屬性
path:網址路徑
name:路由名稱
component:對應的 component 實體
params:欲傳遞的參數
props:欲傳遞的 props 內容
現在將 routes 更改為符合 ProductApp 的設定,並預設導向商品列表頁

export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/product',
name: 'product',
component: () => import('./components/ProductList.vue'),
},
{
path: '/product/:id',
name: 'productInfo',
component: () => import('./components/ProductInfo.vue'),
},
{ path: '*', redirect: '/product' },
],
});

修改 ProductApp component,因為已經改用 Router 方式,將不需要的方法及內容移除,僅留下 template

<template>
<div id="productApp">
<h1>Product App!</h1>
<router-view />
</div>
</template>

router-view 即是作為 router 控制的顯示內容,當 router 變更時,router-view 會顯示為 router 對應的
component 內容

接著更改 ProductList 按下商品後的觸發事件,在 onProductClick 方法改為使用 router 導頁

<script>
export default {
..
methods: {
onProductClick(product) {
this.$router.push({ name: 'productInfo', params: { id: product.id } });
},
},
}
</script>

$router.push 即為導頁的實作方法,在傳入的 options 中放入欲導頁的 router 名稱,以及queryParams 物件,
這裡只需要傳入商品 ID 即可

接著在 ProductInfo 加入回到上一頁的功能以回到商品列表頁

<template>
<div>
<button class="link" @click="onBackClick">
<i class="arrow-left"></i> Back
</button>
...
</div>
</template>
<script>
export default {
...
methods: {
onBackClick() {
this.$router.back();
},
},
}
</script>
<style scoped>
.link {
margin: 5px;
display: inline-block;
padding: 6px 12px;
font-size: 14px;
text-align: center;
text-decoration: underline;
border: none;
font-weight: 400;
color: #337ab7;
background-color: #fff;
}
.link:hover {
cursor: pointer;
}
.arrow-left {
border: solid;
border-width: 0 2px 2px 0;
display: inline-block;
padding: 3px;
-webkit-transform: rotate(135deg);
transform: rotate(135deg);
}
...
</style>

利用 $router.back() 來達到回到上一頁的目的

儲存後在網址後方加入 /product 來導至商品列表頁,並按下商品項目進入商品詳情頁,此時因為無法取得商品內
容,商品詳情還無法正常顯示,但我們已經完成了透過 Router 來切換頁面的功能


上一篇
17.建立商品詳情內容3
下一篇
19.利用 service 處理資料服務
系列文
Vue菜鳥的自我學習days39
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言