商品詳情頁面
- 商品詳情組件
- 發送請求獲取相應商品詳情信息
- 組件展示數據
- 優化一下路由配置代碼
- 滾輪自動置頂
商品詳情組件
- 路由配置
點擊商品進行跳轉—將Detail組件變成路由組件
從商品到詳情,肯定需要傳參(產品ID)告訴Detail是哪個商品,需要展示哪個商品的詳情
在router路由配置中{ path:‘/detail/:id’, component:Detail }
- 復習一下:聲明式路由跳轉傳遞參數
①模板字符串:
<!--query參數?區分,多個參數&間隔-->
<router-link :to="`/detail/?id=${goodList.id}`"><router-link/>
<!--params參數/區分,需要在路由配置中添加/:占位符-->
<router-link :to="`/about/detail/content/${msg.id}/${msg.message}`"></router-link>
②對象:
<router-link :to="{path:'/detail',query:{id: goodList.id}
}">
<router-link :to="{name:'Detail',params:{id: goodList.id}
}"></router-link>
- 商品跳轉router-link
在goodList中:點擊商品圖片就可以跳轉到Detail組件,并傳遞商品id
<router-link :to="`/detail/${goodList.id}`"><img :src='goodList.img'/></router-link>
發送請求獲取相應商品詳情信息
①API—>請求接口封裝函數
接口URL:/api/item/{id} get請求
//api/index.js
export const reqGoodsInfo = id=>requests({url:`item/${id}`},method:'get');
②vuex—>獲取產品信息
vuex中新增一個小模塊detail,然后合并到大倉庫(import 然后modules中添加detail)
//store/detail/index.js
import {reqGoodsInfo} from '@/api';
const state={goodInfo:{}//看返回的結果是對象還是數組
};
const actions={asyn getGoodInfo ({commit},id){let result = await reqGoodsInfo(id);if(result.code==200){commit('GETGOODINFO',result.data);}}
};
const mutations={GETGOODINFO(state,goodInfo){state.goodInfo = goodInfo;}
};
export default{state,actions,mutations
}
③派發action
在detail組件掛載完畢派發actions
mounted(){
this. s t o r e . d i s p a t h ( ′ g e t G o o d I n f o ′ , t h i s . store.dispath('getGoodInfo',this. store.dispath(′getGoodInfo′,this.route.params.id)
}
組件展示數據
獲取到倉庫數據
組件獲取數據state.detail.goodInfo.categoryView
可以通過getters簡化
//detail倉庫
const getters={categoryView(){return state.goodInfo.categoryView}
}
問題:getters計算屬性依賴于state中的數據,但以上寫法會出現警告錯誤。最開始倉庫還未發送請求返回回來數據,goodInfo初始值是空對象,那么getters無法取到categoryView數據,準確寫法
state.goodInfo.categoryView||{}
之后的數據同理
skuInfo(){return state.goodInfo.skuInfo||{};}
最后通過mapState映射數據到組件上
優化一下路由配置代碼
router/index.js中路由配置信息很多,以及import各自組件
將routes:[……]中右邊數組單獨放在一個模塊routes.js對外暴露
//router/routes.js
//路由配置信息
import……
export default [{path:'/home',component:Home}
]
然后看著就很清晰
//router/index.js
import routes from '/routes.js'
export default new VueRouter({//routes: routes key-value一致省略valueroutes
})
滾輪自動置頂
當從商品頁跳到商品詳情頁時,滾輪從原來商品頁的位置到置頂位置
Vue Router里面有個滾動行為,就可以實現自定義路由切換時頁面如何滾動
const router = new VueRouter({routes,//滾動行為scrollBehavior(to, from, savedPosition){//y:0表示滾動條在最頂部//y:100 表示滾動條距離頂部100像素return {y:0}}
})