category.vue 1.99 KB
<template>
	<div class="category-box" ref="scrollBox" v-if="category && category.list">
		<div class="box" ref="scrollItemsBox" :style="'width: ' + scrollItemBox + 'vw'">
			<div class="item" :class="{'active': category.params.pid == item.id}" v-for="(item, index) in category.list" :key="index" @click="change(item)">
				{{item.title}}
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				basicWidth: 92,
				scrollItemBox: 92
			};
		},
		props: ["category"],
		methods: {
			
			/**
			 * 切换分类
			 * @param {object} item [分类项目对象]
			 */
			change(item) {
				if (typeof this.category === "object" && typeof this.category.funcs === "object" && typeof this.category.funcs.change === "function") {
					this.category.funcs.change(item);
				}
			}
		},
		watch: {

			/**
			 * 监听分类列表变化
			 */
			"category.list"(newVal, oldVal) {

				this.$nextTick(() => {
					
					// 判断如果有列表数据再执行
					if (newVal && newVal.length) {

						// box滚动元素宽度,item对象
						let scrollItemBox = 0;
						let clientWidth = this.$refs.scrollBox.clientWidth;
						let multiple = clientWidth / 750;
						let childrens = this.$refs.scrollItemsBox.children;
						
						// 遍历子元素,获取box宽度
						for (let i = 0; i < childrens.length; i++) {
							scrollItemBox += childrens[i].clientWidth;
						}

						// 根据屏幕比例计算实际设置vw值
						scrollItemBox = (scrollItemBox + ((60 * multiple * (childrens.length - 1)))) / clientWidth * this.basicWidth;

						// 判断scrollItemBox值,更新this.scrollItemBox宽度
						if (scrollItemBox > this.basicWidth) {
							this.$set(this, "scrollItemBox", scrollItemBox + (scrollItemBox * 0.03));
						} else {
							this.$set(this, "scrollItemBox", this.basicWidth);
						}
					}
				});
			}
		}
	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style rel="stylesheet/less" lang="less" scoped>
	@import './category';
</style>