Sku.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /* eslint-disable camelcase */
  2. import Vue from 'vue';
  3. import Popup from '../popup';
  4. import Toast from '../toast';
  5. import ImagePreview from '../image-preview';
  6. import SkuHeader from './components/SkuHeader';
  7. import SkuRow from './components/SkuRow';
  8. import SkuRowItem from './components/SkuRowItem';
  9. import SkuStepper from './components/SkuStepper';
  10. import SkuMessages from './components/SkuMessages';
  11. import SkuActions from './components/SkuActions';
  12. import { use, isDef } from '../utils';
  13. import { isAllSelected, isSkuChoosable, getSkuComb, getSelectedSkuValues } from './utils/skuHelper';
  14. import { LIMIT_TYPE, UNSELECTED_SKU_VALUE_ID } from './constants';
  15. const [sfc] = use('sku');
  16. const { QUOTA_LIMIT } = LIMIT_TYPE;
  17. export default sfc({
  18. props: {
  19. sku: Object,
  20. goods: Object,
  21. quota: Number,
  22. value: Boolean,
  23. buyText: String,
  24. quotaUsed: Number,
  25. goodsId: [Number, String],
  26. hideStock: Boolean,
  27. hideQuotaText: Boolean,
  28. stepperTitle: String,
  29. getContainer: Function,
  30. customSkuValidator: Function,
  31. closeOnClickOverlay: Boolean,
  32. disableStepperInput: Boolean,
  33. resetStepperOnHide: Boolean,
  34. resetSelectedSkuOnHide: Boolean,
  35. initialSku: {
  36. type: Object,
  37. default: () => ({})
  38. },
  39. showSoldoutSku: {
  40. type: Boolean,
  41. default: true
  42. },
  43. showAddCartBtn: {
  44. type: Boolean,
  45. default: true
  46. },
  47. bodyOffsetTop: {
  48. type: Number,
  49. default: 200
  50. },
  51. messageConfig: {
  52. type: Object,
  53. default: () => ({
  54. placeholderMap: {},
  55. uploadImg: () => Promise.resolve(),
  56. uploadMaxSize: 5
  57. })
  58. },
  59. customStepperConfig: {
  60. type: Object,
  61. default: () => ({})
  62. },
  63. },
  64. data() {
  65. return {
  66. selectedSku: {},
  67. selectedNum: 1,
  68. show: this.value
  69. };
  70. },
  71. watch: {
  72. show(val) {
  73. this.$emit('input', val);
  74. if (!val) {
  75. const selectedSkuValues = getSelectedSkuValues(this.sku.tree, this.selectedSku);
  76. this.$emit('sku-close', {
  77. selectedSkuValues,
  78. selectedNum: this.selectedNum,
  79. selectedSkuComb: this.selectedSkuComb
  80. });
  81. if (this.resetStepperOnHide) {
  82. this.resetStepper();
  83. }
  84. if (this.resetSelectedSkuOnHide) {
  85. this.resetSelectedSku(this.skuTree);
  86. }
  87. }
  88. },
  89. value(val) {
  90. this.show = val;
  91. },
  92. skuTree(val) {
  93. this.resetSelectedSku(val);
  94. }
  95. },
  96. computed: {
  97. skuGroupClass() {
  98. return [
  99. 'van-sku-group-container',
  100. 'van-hairline--bottom',
  101. {
  102. 'van-sku-group-container--hide-soldout': !this.showSoldoutSku
  103. }
  104. ];
  105. },
  106. bodyStyle() {
  107. if (this.$isServer) {
  108. return;
  109. }
  110. // header高度82px, sku actions高度50px,如果改动了样式自己传下bodyOffsetTop调整下
  111. const maxHeight = window.innerHeight - this.bodyOffsetTop;
  112. return {
  113. maxHeight: maxHeight + 'px'
  114. };
  115. },
  116. isSkuCombSelected() {
  117. return isAllSelected(this.sku.tree, this.selectedSku);
  118. },
  119. isSkuEmpty() {
  120. return Object.keys(this.sku).length === 0;
  121. },
  122. hasSku() {
  123. return !this.sku.none_sku;
  124. },
  125. selectedSkuComb() {
  126. if (!this.hasSku) {
  127. return {
  128. id: this.sku.collection_id,
  129. price: Math.round(this.sku.price * 100),
  130. stock_num: this.sku.stock_num
  131. };
  132. }
  133. if (this.isSkuCombSelected) {
  134. return getSkuComb(this.sku.list, this.selectedSku);
  135. }
  136. return null;
  137. },
  138. price() {
  139. if (this.selectedSkuComb) {
  140. return (this.selectedSkuComb.price / 100).toFixed(2);
  141. }
  142. // sku.price是一个格式化好的价格区间
  143. return this.sku.price;
  144. },
  145. skuTree() {
  146. return this.sku.tree || [];
  147. },
  148. imageList() {
  149. const imageList = [this.goods.picture];
  150. if (this.skuTree.length > 0) {
  151. const treeItem = this.skuTree.filter(item => item.k_s === 's1')[0] || {};
  152. if (!treeItem.v) {
  153. return;
  154. }
  155. treeItem.v.forEach(vItem => {
  156. const img = vItem.imgUrl || vItem.img_url;
  157. if (img) {
  158. imageList.push(img);
  159. }
  160. });
  161. }
  162. return imageList;
  163. }
  164. },
  165. created() {
  166. const skuEventBus = new Vue();
  167. this.skuEventBus = skuEventBus;
  168. skuEventBus.$on('sku:close', this.onClose);
  169. skuEventBus.$on('sku:select', this.onSelect);
  170. skuEventBus.$on('sku:numChange', this.onNumChange);
  171. skuEventBus.$on('sku:previewImage', this.onPreviewImage);
  172. skuEventBus.$on('sku:overLimit', this.onOverLimit);
  173. skuEventBus.$on('sku:addCart', this.onAddCart);
  174. skuEventBus.$on('sku:buy', this.onBuy);
  175. this.resetStepper();
  176. this.resetSelectedSku(this.skuTree);
  177. // 组件初始化后的钩子,抛出skuEventBus
  178. this.$emit('after-sku-create', skuEventBus);
  179. },
  180. methods: {
  181. resetStepper() {
  182. const { skuStepper } = this.$refs;
  183. const { selectedNum } = this.initialSku;
  184. const num = isDef(selectedNum) ? selectedNum : 1;
  185. if (skuStepper) {
  186. skuStepper.setCurrentNum(num);
  187. } else {
  188. this.selectedNum = num;
  189. }
  190. },
  191. resetSelectedSku(skuTree) {
  192. this.selectedSku = {};
  193. // 重置 selectedSku
  194. skuTree.forEach(item => {
  195. this.selectedSku[item.k_s] = this.initialSku[item.k_s] || UNSELECTED_SKU_VALUE_ID;
  196. });
  197. // 只有一个 sku 规格值时默认选中
  198. skuTree.forEach(item => {
  199. const key = item.k_s;
  200. const valueId = item.v[0].id;
  201. if (
  202. item.v.length === 1 &&
  203. isSkuChoosable(this.sku.list, this.selectedSku, { key, valueId })
  204. ) {
  205. this.selectedSku[key] = valueId;
  206. }
  207. });
  208. },
  209. getSkuMessages() {
  210. return this.$refs.skuMessages ? this.$refs.skuMessages.getMessages() : {};
  211. },
  212. getSkuCartMessages() {
  213. return this.$refs.skuMessages ? this.$refs.skuMessages.getCartMessages() : {};
  214. },
  215. validateSkuMessages() {
  216. return this.$refs.skuMessages ? this.$refs.skuMessages.validateMessages() : '';
  217. },
  218. validateSku() {
  219. if (this.selectedNum === 0) {
  220. return '商品已经无法购买啦';
  221. }
  222. if (this.isSkuCombSelected) {
  223. return this.validateSkuMessages();
  224. }
  225. // 自定义sku校验
  226. if (this.customSkuValidator) {
  227. const err = this.customSkuValidator(this);
  228. if (err) return err;
  229. }
  230. return '请先选择商品规格';
  231. },
  232. onClose() {
  233. this.show = false;
  234. },
  235. onSelect(skuValue) {
  236. // 点击已选中的sku时则取消选中
  237. this.selectedSku =
  238. this.selectedSku[skuValue.skuKeyStr] === skuValue.id
  239. ? { ...this.selectedSku, [skuValue.skuKeyStr]: UNSELECTED_SKU_VALUE_ID }
  240. : { ...this.selectedSku, [skuValue.skuKeyStr]: skuValue.id };
  241. this.$emit('sku-selected', {
  242. skuValue,
  243. selectedSku: this.selectedSku,
  244. selectedSkuComb: this.selectedSkuComb
  245. });
  246. },
  247. onNumChange(num) {
  248. this.selectedNum = num;
  249. },
  250. onPreviewImage(indexImage) {
  251. const index = this.imageList.findIndex(image => image === indexImage);
  252. const cbParams = {
  253. index,
  254. imageList: this.imageList,
  255. indexImage
  256. };
  257. this.$emit('preview-on', cbParams);
  258. ImagePreview({
  259. images: this.imageList,
  260. startPosition: index,
  261. onClose: () => {
  262. this.$emit('preview-close', cbParams);
  263. }
  264. });
  265. },
  266. onOverLimit(data) {
  267. const { action, limitType, quota, quotaUsed } = data;
  268. const { handleOverLimit } = this.customStepperConfig;
  269. if (handleOverLimit) {
  270. handleOverLimit(data);
  271. return;
  272. }
  273. if (action === 'minus') {
  274. Toast('至少选择一件');
  275. } else if (action === 'plus') {
  276. if (limitType === QUOTA_LIMIT) {
  277. let msg = `限购${quota}件`;
  278. if (quotaUsed > 0) msg += `,${`你已购买${quotaUsed}件`}`;
  279. Toast(msg);
  280. } else {
  281. Toast('库存不足');
  282. }
  283. }
  284. },
  285. onAddCart() {
  286. this.onBuyOrAddCart('add-cart');
  287. },
  288. onBuy() {
  289. this.onBuyOrAddCart('buy-clicked');
  290. },
  291. onBuyOrAddCart(type) {
  292. const error = this.validateSku();
  293. if (error) {
  294. Toast(error);
  295. } else {
  296. this.$emit(type, this.getSkuData());
  297. }
  298. },
  299. getSkuData() {
  300. return {
  301. goodsId: this.goodsId,
  302. selectedNum: this.selectedNum,
  303. selectedSkuComb: this.selectedSkuComb,
  304. messages: this.getSkuMessages(),
  305. cartMessages: this.getSkuCartMessages()
  306. };
  307. }
  308. },
  309. render(h) {
  310. if (this.isSkuEmpty) {
  311. return;
  312. }
  313. const {
  314. sku,
  315. goods,
  316. price,
  317. skuEventBus,
  318. selectedSku,
  319. selectedNum,
  320. stepperTitle,
  321. hideQuotaText,
  322. selectedSkuComb
  323. } = this;
  324. const slotsProps = {
  325. price,
  326. selectedNum,
  327. skuEventBus,
  328. selectedSku,
  329. selectedSkuComb
  330. };
  331. const slots = name => this.slots(name, slotsProps);
  332. const Header = slots('sku-header') || (
  333. <SkuHeader sku={sku} goods={goods} skuEventBus={skuEventBus} selectedSku={selectedSku}>
  334. {slots('sku-header-price') || (
  335. <div class="van-sku__goods-price">
  336. <span class="van-sku__price-symbol">¥</span>
  337. <span class="van-sku__price-num">{price}</span>
  338. </div>
  339. )}
  340. </SkuHeader>
  341. );
  342. const Group =
  343. slots('sku-group') ||
  344. (this.hasSku && (
  345. <div class={this.skuGroupClass}>
  346. {this.skuTree.map(skuTreeItem => (
  347. <SkuRow skuRow={skuTreeItem}>
  348. {skuTreeItem.v.map(skuValue => (
  349. <SkuRowItem
  350. skuList={sku.list}
  351. skuValue={skuValue}
  352. selectedSku={selectedSku}
  353. skuEventBus={skuEventBus}
  354. skuKeyStr={skuTreeItem.k_s}
  355. />
  356. ))}
  357. </SkuRow>
  358. ))}
  359. </div>
  360. ));
  361. const Stepper = slots('sku-stepper') || (
  362. <SkuStepper
  363. ref="skuStepper"
  364. quota={this.quota}
  365. hideStock={this.hideStock}
  366. quotaUsed={this.quotaUsed}
  367. skuEventBus={skuEventBus}
  368. selectedNum={selectedNum}
  369. selectedSku={selectedSku}
  370. stepperTitle={stepperTitle}
  371. skuStockNum={sku.stock_num}
  372. hideQuotaText={hideQuotaText}
  373. selectedSkuComb={selectedSkuComb}
  374. disableStepperInput={this.disableStepperInput}
  375. customStepperConfig={this.customStepperConfig}
  376. onChange={event => {
  377. this.$emit('stepper-change', event);
  378. }}
  379. />
  380. );
  381. const Messages = slots('sku-messages') || (
  382. <SkuMessages
  383. ref="skuMessages"
  384. goodsId={this.goodsId}
  385. messageConfig={this.messageConfig}
  386. messages={sku.messages}
  387. />
  388. );
  389. const Actions = slots('sku-actions') || (
  390. <SkuActions
  391. buyText={this.buyText}
  392. skuEventBus={skuEventBus}
  393. showAddCartBtn={this.showAddCartBtn}
  394. />
  395. );
  396. return (
  397. <Popup
  398. vModel={this.show}
  399. position="bottom"
  400. class="van-sku-container"
  401. getContainer={this.getContainer}
  402. closeOnClickOverlay={this.closeOnClickOverlay}
  403. >
  404. {Header}
  405. <div class="van-sku-body" style={this.bodyStyle}>
  406. {slots('sku-body-top')}
  407. {Group}
  408. {slots('extra-sku-group')}
  409. {Stepper}
  410. {Messages}
  411. </div>
  412. {Actions}
  413. </Popup>
  414. );
  415. }
  416. });