共计 2425 个字符,预计需要花费 7 分钟才能阅读完成。
上篇我们将菜单栏,商品展示结构完成,本次我们为这两个部分接入数据。
菜单栏接入数据
导入组件,定义需要的数据格式
<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 钩子发起请求获取数据
之前我们说过在 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 更新后。我们执行初始化滚动函数。
https://cn.vuejs.org/v2/api/#…
通过 methods 定义我们需要的方法
- 通过 head_bg(imgName) 方法获取到商品的背景图片;
- 方法 initScroll() 用来初始化滚动,https://cn.vuejs.org/v2/api/#ref;
- calculateHeight() 方法获取左侧每一个菜单栏目的元素;
-
使用 selectMenu() 方法,在我们点击菜单后,右侧显示对应的商品信息;
methods: {
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; } },
以上我们完成了商品页面数据的交互,下一篇我们将加入商品控件,与购物车。
正文完
发表至: javascript
2019-07-13