上篇咱們將菜單欄,商品展現結構完成,本次咱們爲這兩個部分接入數據。vue
菜單欄接入數據ios
導入組件,定義須要的數據格式axios
<script> // 導入BScroll 滾動組件 import BScroll from "better-scroll"; // 導入Food 商品頁面 import Food from "components/Food/Food"; export default { data() { //準備須要的數據,初始化組件。 return { container: {}, goods: [], poiInfo: {}, listHeight: [], scrollY: 0, menuScroll: {}, foodScroll: {}, selectedFood: {} }; }, //引用組件 components: { BScroll, Food } }; </script>
經過created鉤子發起請求獲取數據api
以前咱們說過在created鉤子,mounted鉤子內能夠發起請求,請求須要的數據。本次咱們在created鉤子內發起get請求,獲取數據數組
created() { //經過that改變.then中的this指向 var that = this; // 經過axios發起get請求 this.$axios .get("/api/goods") .then(function(response) { // 獲取到數據 var dataSource = response.data; if (dataSource.code == 0) { that.container = dataSource.data.container_operation_source; that.goods = dataSource.data.food_spu_tags; that.poiInfo = dataSource.data.poi_info; // 調用滾動的初始化方法 // that.initScroll(); // 開始時,DOM元素沒有渲染,即高度是問題 // 在獲取到數據後,並DOM已經被渲染,表示列表高度是沒問題的 // nextTick that.$nextTick(() => { // DOM已經更新 that.initScroll(); // 計算分類區間高度 that.calculateHeight(); }); } }) .catch(function(error) { // 出錯處理 console.log(error); }); },
注意$nextTick()用法,在dom更新後。咱們執行初始化滾動函數。dom
https://cn.vuejs.org/v2/api/#...函數
經過methods定義咱們須要的方法this
使用selectMenu()方法,在咱們點擊菜單後,右側顯示對應的商品信息;url
methods: {spa
head_bg(imgName) { return "background-image: url(" + imgName + ");"; }, // 滾動的初始化 initScroll() { // ref屬性就是用來綁定某個dom元素或某個組件,而後在this.$refs裏面 this.menuScroll = new BScroll(this.$refs.menuScroll, { click: true }); this.foodScroll = new BScroll(this.$refs.foodScroll, { probeType: 3, click: true }); // 添加滾動監聽事件 this.foodScroll.on("scroll", pos => { this.scrollY = Math.abs(Math.round(pos.y)); }); }, calculateHeight() { // 經過$refs獲取到對應的元素 let foodlist = this.$refs.foodScroll.getElementsByClassName( "food-list-hook" ); // 添加到數組區間 // 0~216 第一個區間(專場) // 217~1342 第二個區間(熱銷) let height = 0; this.listHeight.push(height); for (let i = 0; i < foodlist.length; i++) { let item = foodlist[i]; // 累加 height += item.clientHeight; this.listHeight.push(height); } }, selectMenu(index) { let foodlist = this.$refs.foodScroll.getElementsByClassName( "food-list-hook" ); // 根據下標,滾動到相對應的元素 let el = foodlist[index]; // 滾動到對應元素的位置 this.foodScroll.scrollToElement(el, 250); }
},
computed定義屬性
currentIndex屬性綁定在左側菜單欄,使菜單元素與右側內容做爲對應,展現給用戶。
computed: {
currentIndex() { // 根據右側滾動位置,肯定對應的索引下標 for (let i = 0; i < this.listHeight.length; i++) { // 獲取商品區間的範圍 let height1 = this.listHeight[i]; let height2 = this.listHeight[i + 1]; // 是否在上述區間中 if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) { return i; } } return 0; } },
以上咱們完成了商品頁面數據的交互,下一篇咱們將加入商品控件,與購物車。