【vue3.0】18.0 某东到家(十八)——优化代码、数据永久性存储localStorage

目的:打造购物车的页面

"去结算"调整

调整src\views\shop\Cart.vue

<template>
......
      <div class="check__btn">
        <router-link :to="{ name: 'Home' }">
          去结算
        </router-link>
      </div>
    </div>
  </div>
</template>
......
<style lang="scss" scoped>
......
.check {
......
  &__btn {
......
    // 去掉a标签的下划线
    a {
      color: $bg-color;
      text-decoration: none; //去掉文本修饰
    }
  }
}
</style>

优化if语句

src\store\index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    cartList: {
      // 第一层级:商铺的id
      // 第二层内容是商品内容以及购物数量
      // shopId: {
      //   productID: {
      //     _id: '1',
      //     name: '番茄250g/份',
      //     imgUrl: '/i18n/9_16/img/tomato.png',
      //     sales: 10,
      //     price: 33.6,
      //     oldPrice: 39.6,
      //     count: 0
      //   }
      // }
    }
  },
  mutations: {
    /**
     * 加入或减少购物车数量
     * @param {*} state
     * @param {String} shopId 店铺id
     * @param {String} productId 商品id
     * @param {Object} productInfo 商品信息集
     * @param {Number} num 加入购物车的数量
     * @param {*} payload
     */
    changeItemToCart(state, payload) {
      const { shopId, productId, productInfo, num } = payload
      // console.log(shopId, productId, productInfo)
      const shopInfo = state.cartList[shopId] || {}

      let product = shopInfo[productId]
      if (!product) {
        productInfo.count = 0
        product = productInfo // 初始化
      }

      product.count += num
      // && 短路运算符,前面的满足才会执行后面的逻辑,等价于if
      num > 0 && (product.checked = true)

      product.count <= 0 && (shopInfo[productId].count = 0)
      // delete state.cartList[shopId]

      shopInfo[productId] = product
      // 赋值
      state.cartList[shopId] = shopInfo
    },
    // 购物车勾选记录
    changeItemChecked(state, payload) {
      const { shopId, productId } = payload
      const product = state.cartList[shopId][productId]
      product.checked = !product.checked
    },
    // 清除购物车
    changeCleanCartProducts(state, payload) {
      const { shopId } = payload
      state.cartList[shopId] = {}
    },
    // 购物车全选或者取消全选
    setCartItemsChecked(state, payload) {
      const { shopId } = payload
      const products = state.cartList[shopId]
      if (products) {
        for (const i in products) {
          const product = products[i]
          product.checked = true
        }
      }
    }
  },
  actions: {},
  modules: {}
})

之前存入src\store\index.js

      // 第一层级:商铺的id
      // 第二层内容是商品内容以及购物数量
      // shopId: {
      //   productID: {
      //     _id: '1',
      //     name: '番茄250g/份',
      //     imgUrl: '/i18n/9_16/img/tomato.png',
      //     sales: 10,
      //     price: 33.6,
      //     oldPrice: 39.6,
      //     count: 0
      //   }
      // }

在订单层面,需要显示商品名字等商铺的信息,明显这个结构不够用。优化结构如下:

      // shopId: {
      //   shopName: '沃什么码',
      //   productList: {
      //     productId: {
      //       _id: '1',
      //       name: '番茄250g/份',
      //       imgUrl: '/i18n/9_16/img/tomato.png',
      //       sales: 10,
      //       price: 33.6,
      //       oldPrice: 39.6,
      //       count: 0
      //     }
      //   }
      // }

那么相应的更新代码也要调整:
src\store\index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    cartList: {
      // shopId: {
      //   shopName: '沃什么码',
      //   productList: {
      //     productId: {
      //       _id: '1',
      //       name: '番茄250g/份',
      //       imgUrl: '/i18n/9_16/img/tomato.png',
      //       sales: 10,
      //       price: 33.6,
      //       oldPrice: 39.6,
      //       count: 0
      //     }
      //   }
      // }
      // ================== 之前版本的结构 ==================
      // 第一层级:商铺的id
      // 第二层内容是商品内容以及购物数量
      // shopId: {
      //   productID: {
      //     _id: '1',
      //     name: '番茄250g/份',
      //     imgUrl: '/i18n/9_16/img/tomato.png',
      //     sales: 10,
      //     price: 33.6,
      //     oldPrice: 39.6,
      //     count: 0
      //   }
      // }
    }
  },
  mutations: {
    /**
     * 加入或减少购物车数量
     * @param {*} state
     * @param {String} shopId 店铺id
     * @param {String} productId 商品id
     * @param {Object} productInfo 商品信息集
     * @param {Number} num 加入购物车的数量
     * @param {*} payload
     */
    changeItemToCart(state, payload) {
      const { shopId, productId, productInfo, num } = payload
      // console.log(shopId, productId, productInfo)
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }

      let product = shopInfo?.productList[productId]
      if (!product) {
        productInfo.count = 0
        product = productInfo // 初始化
      }

      product.count += num
      // && 短路运算符,前面的满足才会执行后面的逻辑,等价于if
      num > 0 && (product.checked = true)

      product.count <= 0 && (shopInfo[productId].count = 0)
      // delete state.cartList[shopId]

      shopInfo.productList[productId] = product
      // 赋值
      state.cartList[shopId] = shopInfo
    },
    // 购物车勾选记录
    changeItemChecked(state, payload) {
      const { shopId, productId } = payload
      const product = state.cartList[shopId].productList[productId]
      product.checked = !product.checked
    },
    // 清除购物车
    changeCleanCartProducts(state, payload) {
      const { shopId } = payload
      state.cartList[shopId].productList = {}
    },
    // 购物车全选或者取消全选
    setCartItemsChecked(state, payload) {
      const { shopId } = payload
      const products = state.cartList[shopId].productList
      if (products) {
        for (const i in products) {
          const product = products[i]
          product.checked = true
        }
      }
    },
    /**
     * 修改商店名称
     * @param {Object} state vuex对象
     * @param {Object} payload 传值
     */
    changeShopName(state, payload) {
      const { shopId, shopName } = payload
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
    }
  },
  actions: {},
  modules: {}
})

src\views\shop\Shop.vue

<template>
  <div class="wrapper">
    <div class="search">
      <div class="search__back" @click="handleBackClick">
        <i class="search__back__icon custom-icon custom-icon-back"></i>
      </div>
      <div class="search__content">
        <span
          ><i class="search__content__icon custom-icon custom-icon-search"></i
        ></span>
        <input class="search__content__input" placeholder="请输入商品名称" />
      </div>
    </div>
    <!-- v-show="item.headImg"  防止撕裂图片的出现 -->
    <ShopInfo :item="item" :hideBorder="true" v-if="item.headImg" />
    <Content :shopName="item.title" />
    <Cart />
    <Toast v-if="show" :message="message" />
  </div>
</template>

<script>
import { reactive, toRefs, nextTick } from 'vue' // 路由跳转方法
import { useRouter, useRoute } from 'vue-router'
import ShopInfo from '@/components/ShopInfo/ShopInfo'
import { get } from '@/utils/request.js'
import Toast, { useToastEffect } from '@/components/Toast/Toast'
import Content from '@/views/shop/Content'
import Cart from '@/views/shop/Cart'

// 获取当前商铺信息
const useShopInfoEffect = (toastMsg, route) => {
  const data = reactive({ item: {} })
  // eslint-disable-next-line no-unused-vars
  const getItemData = async () => {
    // 可以写成: const resultData = await get(`/api/shop/${route.params.id}`)
    console.log(' route.params.id:' + route.params.id)
    const resultData = await get('/api/shop/' + route.params.id)
    if (resultData?.code === 200 && resultData?.data) {
      data.item = {
        id: resultData.data?.id,
        title: resultData.data?.name,
        sales: resultData.data?.sales,
        headImg: resultData.data?.imgUrl,
        expressLimit: resultData.data?.expressLimit,
        expressPrice: resultData.data?.expressPrice,
        highlight: resultData.data?.slogon
      }
      console.log('data.item :' + JSON.stringify(data.item))
      nextTick()
    } else {
      toastMsg('没有数据!')
    }
  }
  const { item } = toRefs(data)
  return { item, getItemData }
}

// 后退按钮事件
const useBackRouterEffect = router => {
  const handleBackClick = () => {
    router.back()
  }
  return { handleBackClick }
}

export default {
  name: 'Shop',
  components: { ShopInfo, Toast, Content, Cart },
  // eslint-disable-next-line space-before-function-paren
  setup() {
    const router = useRouter() // 整个大路由的信息
    const route = useRoute() // 当前访问路径的信息

    const { show, message, toastMsg } = useToastEffect()
    const { item, getItemData } = useShopInfoEffect(toastMsg, route)
    const { handleBackClick } = useBackRouterEffect(router)
    getItemData()
    return { show, message, item, handleBackClick }
  }
}
</script>

<style lang="scss" scoped>
@import '@/style/viriables';
.wrapper {
  padding: 0 0.18rem;
}
.search {
  margin: 0.14rem 0 0.04rem 0;
  display: flex;
  line-height: 0.32rem; //高度会将父元素撑开
  &__back {
    width: 0.3rem;
    &__icon {
      font-size: 0.2rem;
      color: #b6b6b6;
    }
  }
  &__content {
    display: flex;
    flex: 1;
    background: $search-bg-color;
    border-radius: 0.16rem;
    &__icon {
      padding-left: 0.1rem;
      padding-right: 0.1rem;
      width: 0.44rem;
      text-align: center;
      color: $search-font-color;
    }
    &__input {
      padding-right: 0.2rem;
      width: 100%;
      display: block;
      border: none;
      outline: none;
      background: none;
      height: 0.32rem;
      font-size: 0.14rem;
      color: $content-font-color;
      &::placeholder {
        color: $content-font-color;
      }
    }
  }
}
</style>

src\views\shop\Content.vue

<template>
  <div class="content">
    <div class="category">
      <div
        :class="{
          category__item: true,
          'category__item--active': currentTab === item.tab
        }"
        v-for="item in categories"
        :key="item.tab"
        @click="handleTabClick(item.tab)"
      >
        {{ item.name }}
      </div>
    </div>
    <div class="product">
      <div class="product__item" v-for="item in list" :key="item._id">
        <img class="product__item__img" :src="item.imgUrl" />
        <div class="product__item__detail">
          <h4 class="product__item__title">{{ item.name }}</h4>
          <p class="product__item__sales">月售{{ item.sales }}件</p>
          <p class="product__item__price">
            <span class="product__item__yen"> &yen;{{ item.price }} </span>
            <span class="product__item__origin">
              &yen;{{ item.oldPrice }}
            </span>
          </p>
        </div>
        <div class="product__number">
          <span
            class="product__number__minus"
            @click="
              () => {
                changeCartItem(shopId, item._id, item, -1, shopName)
              }
            "
            >-</span
          >
          {{ cartList?.[shopId]?.productList.[item._id]?.count || 0 }}
          <span
            class="product__number__plus"
            @click="
              () => {
                changeCartItem(shopId, item._id, item, 1, shopName)
              }
            "
            >+</span
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, ref, toRefs, watchEffect } from 'vue'
import { useRoute } from 'vue-router' // 路由跳转方法
import { useStore } from 'vuex'
import { get } from '@/utils/request.js'
import { useCommonCartEffect } from './commnCartEffect'

const categories = [
  {
    name: '全部商品',
    tab: 'all'
  },
  {
    name: '秒杀',
    tab: 'seckill'
  },
  {
    name: '新鲜水果',
    tab: 'fruit'
  },
  {
    name: '休闲食品',
    tab: 'snack'
  }
]

// 和tab切换相关的逻辑
const useTabEffect = () => {
  const currentTab = ref(categories[0].tab)
  const handleTabClick = tab => {
    console.log('click:' + tab)
    currentTab.value = tab
  }
  return { currentTab, handleTabClick }
}
// 当前列表内容相关的函数
const useContentListEffect = (currentTab, shopId) => {
  const content = reactive({ list: [] })
  const getContentData = async () => {
    const result = await get(`/api/shop/${shopId}/products`, {
      tab: currentTab.value
    })
    console.log('result:' + result)
    if (result?.code === 200 && result?.data?.length) {
      content.list = result.data
    }
  }
  // watchEffect:当首次页面加载时,或当其中监听的数据发生变化时执行
  watchEffect(() => {
    getContentData()
  })
  const { list } = toRefs(content)
  return { list }
}

export default {
  name: 'Content',
  props: {
    id: String,
    shopName: String
  },
  setup() {
    const route = useRoute() // 获取路由
    const store = useStore()
    const shopId = route.params.id
    const { currentTab, handleTabClick } = useTabEffect()
    const { list } = useContentListEffect(currentTab, shopId)
    const { cartList, changeCartItemInfo } = useCommonCartEffect()

    const changeShopName = (shopId, shopName) => {
      store.commit('changeShopName', { shopId, shopName })
    }
    const changeCartItem = (shopId, productId, item, num, shopName) => {
      changeCartItemInfo(shopId, productId, item, num)
      changeShopName(shopId, shopName)
    }
    return {
      cartList,
      list,
      categories,
      handleTabClick,
      currentTab,
      shopId,
      changeCartItem,
      changeCartItemInfo
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/style/viriables.scss';
@import '@/style/mixins.scss';
.content {
  display: flex;
  position: absolute;
  left: 0;
  right: 0;
  top: 1.6rem;
  bottom: 0.5rem;
}
.category {
  overflow-y: scroll;
  width: 0.76rem;
  background: $search-bg-color;
  height: 100%;
  &__item {
    line-height: 0.4rem;
    text-align: center;
    font-size: 14px;
    color: $content-font-color;
    &--active {
      background: $bg-color;
    }
  }
}
.product {
  overflow-y: scroll;
  flex: 1;
  &__item {
    position: relative;
    display: flex;
    padding: 0.12rem 0.16rem;
    margin: 0 0.16rem;
    border-bottom: 0.01rem solid $content-bg-color;
    // 配合解决超出长度以省略号显示而不会出现换行
    &__detail {
      overflow: hidden;
    }
    &__img {
      width: 0.68rem;
      height: 0.68rem;
      margin-right: 0.16rem;
    }
    &__title {
      margin: 0;
      line-height: 0.2rem;
      font-size: 0.14rem;
      color: $content-font-color;
      // 超出长度以省略号显示而不会出现换行
      @include ellipsis;
    }
    &__sales {
      margin: 0.06rem 0;
      line-height: 0.16rem;
      font-size: 0.12rem;
      color: $content-font-color;
    }
    &__price {
      margin: 0;
      line-height: 0.2rem;
      font-size: 0.14rem;
      color: $height-light-font-color;
    }
    &__yen {
      font-size: 0.12rem;
    }
    &__origin {
      margin-left: 0.06rem;
      line-height: 0.2rem;
      font-size: 0.12rem;
      color: $light-font-color;
      text-decoration: line-through; //中划线
    }
    // 购物车选购数量和加减号
    .product__number {
      position: absolute;
      right: 0rem;
      bottom: 0.12rem;
      &__minus,
      &__plus {
        display: inline-block;
        width: 0.2rem;
        height: 0.2rem;
        line-height: 0.16rem;
        border-radius: 50%;
        font-size: 0.2rem;
        text-align: center;
      }
      // 边框白色
      &__minus {
        border: 0.01rem solid $medium-font-color;
        color: $medium-font-color;
        margin-right: 0.05rem;
      }
      //无边框,背景蓝色
      &__plus {
        color: $bg-color;
        background: $btn-bg-color;
        margin-left: 0.05rem;
      }
    }
  }
}
</style>

src\views\shop\commnCartEffect.js

import { toRefs } from 'vue'
import { useStore } from 'vuex'
// 添加、减少到购物车功能
export const useCommonCartEffect = () => {
  const store = useStore()
  const { cartList } = toRefs(store.state)
  /**
   * 加入或减少购物车数量
   * @param {String} shopId 店铺id
   * @param {String} productId 商品id
   * @param {Object} productInfo 商品信息集
   * @param {Number} num 加入购物车的数量
   */
  const changeCartItemInfo = (shopId, productId, productInfo, num) => {
    console.log(
      'changeCartItemInfo:',
      'shopId:' + shopId,
      'productId:' + productId,
      'productInfo:' + JSON.stringify(productInfo),
      'num:' + num
    )
    // 更新vuex中的值
    store.commit('changeItemToCart', { shopId, productId, productInfo, num })
  }

  return { cartList, changeCartItemInfo }
}

src\views\shop\Cart.vue

<template>
  <!-- 蒙层 -->
  <div class="mask" v-if="showCart" @click="handleCartShowChange"></div>
  <div class="cart">
    <div class="product" v-show="showCart">
      <div class="product__header">
        <div class="product__header__all" @click="setCartItemsChecked(shopId)">
          <i
            :class="[
              'product__header__all__icon',
              'custom-icon',
              allChecked
                ? 'custom-icon-radio-checked'
                : 'custom-icon-radio-unchecked'
            ]"
          ></i>
          <span class="product__header__all__text">全选</span>
        </div>
        <div class="product__header__clear">
          <span
            class="product__header__clear__btn"
            @click="cleanCartProducts(shopId)"
            >清空购物车</span
          >
        </div>
      </div>
      <template v-for="item in productList" :key="item._id">
        <div class="product__item" v-if="item.count > 0">
          <div
            class="product__item__checked"
            @click="changeCartItemChecked(shopId, item._id)"
          >
            <i
              :class="[
                'custom-icon',
                item.checked == true
                  ? 'custom-icon-radio-checked'
                  : 'custom-icon-radio-unchecked'
              ]"
            ></i>
          </div>
          <img class="product__item__img" :src="item.imgUrl" />
          <div class="product__item__detail">
            <h4 class="product__item__title">{{ item.name }}</h4>
            <p class="product__item__price">
              <span class="product__item__yen"> &yen;{{ item.price }} </span>
              <span class="product__item__origin">
                &yen;{{ item.oldPrice }}
              </span>
            </p>
          </div>
          <div class="product__number">
            <span
              class="product__number__minus"
              @click="
                () => {
                  0
                  changeCartItemInfo(shopId, item._id, item, -1)
                }
              "
              >-</span
            >
            {{ cartList?.[shopId]?.productList.[item._id]?.count || 0 }}
            <span
              class="product__number__plus"
              @click="
                () => {
                  changeCartItemInfo(shopId, item._id, item, 1)
                }
              "
              >+</span
            >
          </div>
        </div>
      </template>
    </div>
    <div class="check">
      <div class="check__icon" @click="handleCartShowChange">
        <img src="/i18n/9_16/img/basket.png" alt="" class="check__icon__img" />
        <div class="check__icon__tag">
          {{ total }}
        </div>
      </div>
      <div class="check__info">
        总计:<span class="check__info__price">&yen; {{ totalPrice }}</span>
      </div>
      <div class="check__btn">
        <router-link :to="{ name: 'Home' }">
          去结算
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router' // 路由跳转方法
import { useStore } from 'vuex' // 路由跳转方法
import { useCommonCartEffect } from './commnCartEffect'

const useCartEffect = shopId => {
  const { changeCartItemInfo } = useCommonCartEffect()
  const store = useStore()

  // 单个勾选或者不勾选
  const changeCartItemChecked = (shopId, productId) => {
    store.commit('changeItemChecked', { shopId, productId })
  }
  // 清除购物车按钮
  const cleanCartProducts = shopId => {
    store.commit('changeCleanCartProducts', { shopId })
  }
  // 购物车全选或者取消全选
  const setCartItemsChecked = shopId => {
    store.commit('setCartItemsChecked', { shopId })
  }

  // 计算shopId下所有cartList的商品数量total、价钱之和totalPrice
  const cartList = store.state.cartList // 加入购物车的商品列表fv
  const total = computed(() => {
    const productList = cartList[shopId]?.productList
    let count = 0
    if (productList) {
      for (const i in productList) {
        const product = productList[i]
        count += product.count
      }
    }
    return count
  })
  const totalPrice = computed(() => {
    const productList = cartList[shopId]?.productList
    let count = 0
    if (productList) {
      for (const i in productList) {
        const product = productList[i]
        if (product.checked === true) {
          count += product.count * product.price
        }
      }
    }
    return count.toFixed(2) // 保留2位小数
  })

  // 全选的计算属性
  const allChecked = computed(() => {
    const productList = cartList[shopId]?.productList
    let result = true
    if (productList) {
      for (const i in productList) {
        const product = productList[i]
        if (product.count > 0 && !product.checked) {
          result = false
          break
        }
      }
    }
    return result
  })

  const productList = computed(() => {
    const productInfoList = cartList[shopId]?.productList || [] // 不存在默认空数组
    return productInfoList
  })
  return {
    cartList,
    total,
    totalPrice,
    productList,
    allChecked,
    changeCartItemChecked,
    changeCartItemInfo,
    cleanCartProducts,
    setCartItemsChecked
  }
}

// 展示隐藏购物车
const toggleCartEffect = () => {
  const showCart = ref(false)
  // 显示隐藏购物车具体内容
  const handleCartShowChange = () => {
    showCart.value = !showCart.value
  }
  return { showCart, handleCartShowChange }
}
export default {
  name: 'Cart',
  setup() {
    const route = useRoute()
    const shopId = route.params.id // 店铺id
    // 展示隐藏购物车
    const { showCart, handleCartShowChange } = toggleCartEffect()
    // 计算总价和加入购物车的总数量
    const {
      cartList,
      total,
      totalPrice,
      productList,
      allChecked,
      changeCartItemChecked,
      changeCartItemInfo,
      cleanCartProducts,
      setCartItemsChecked
    } = useCartEffect(shopId)
    return {
      cartList,
      total,
      totalPrice,
      productList,
      shopId,
      allChecked,
      showCart,
      handleCartShowChange,
      changeCartItemChecked,
      changeCartItemInfo,
      cleanCartProducts,
      setCartItemsChecked
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/style/viriables.scss';
@import '@/style/mixins.scss';
.mask {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1;
}
.cart {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
  background: $bg-color;
}
.product {
  overflow-y: scroll;
  flex: 1;
  background: $bg-color;
  &__header {
    display: flex;
    line-height: 0.52rem;
    border-bottom: 0.01rem solid $content-bg-color;
    font-size: 0.14rem;
    color: $content-font-color;
    &__all {
      width: 0.64rem;
      margin-left: 0.18rem;
      &__icon {
        display: inline-block;
        vertical-align: top;
        font-size: 0.2rem;
        margin-right: 0.05rem;
        color: $btn-bg-color;
      }
      &__text {
        display: inline-block;
        margin-left: 0.04rem;
        line-height: 0.52rem;
      }
    }
    &__clear {
      flex: 1;
      text-align: right;
      margin-right: 0.16rem;
      &__btn {
        display: inline-block;
      }
    }
  }
  &__item {
    position: relative;
    display: flex;
    padding: 0.12rem 0.16rem;
    margin: 0 0.16rem;
    border-bottom: 0.01rem solid $content-bg-color;
    &__checked {
      line-height: 0.5rem;
      margin-right: 0.2rem;
      color: $btn-bg-color;
      i {
        font-size: 0.25rem;
      }
    }
    // 配合解决超出长度以省略号显示而不会出现换行
    &__detail {
      overflow: hidden;
    }
    &__img {
      width: 0.46rem;
      height: 0.46rem;
      margin-right: 0.16rem;
    }
    &__title {
      margin: 0;
      line-height: 0.2rem;
      font-size: 0.14rem;
      color: $content-font-color;
      // 超出长度以省略号显示而不会出现换行
      @include ellipsis;
    }
    &__price {
      margin: 0.06rem 0 0 0;
      line-height: 0.2rem;
      font-size: 0.14rem;
      color: $height-light-font-color;
    }
    &__yen {
      font-size: 0.12rem;
    }
    &__origin {
      margin-left: 0.06rem;
      line-height: 0.2rem;
      font-size: 0.12rem;
      color: $light-font-color;
      text-decoration: line-through; //中划线
    }
    // 购物车选购数量和加减号
    .product__number {
      position: absolute;
      right: 0rem;
      bottom: 0.26rem;
      &__minus,
      &__plus {
        display: inline-block;
        width: 0.2rem;
        height: 0.2rem;
        line-height: 0.16rem;
        border-radius: 50%;
        font-size: 0.2rem;
        text-align: center;
      }
      // 边框白色
      &__minus {
        border: 0.01rem solid $medium-font-color;
        color: $medium-font-color;
        margin-right: 0.05rem;
      }
      //无边框,背景蓝色
      &__plus {
        color: $bg-color;
        background: $btn-bg-color;
        margin-left: 0.05rem;
      }
    }
  }
}
.check {
  display: flex;
  box-sizing: border-box; //往内塞入border
  line-height: 0.49rem;
  height: 0.49rem;
  border-top: 0.01rem solid $content-bg-color;
  &__icon {
    width: 0.84rem;
    position: relative;
    &__img {
      margin: 0.12rem auto;
      display: block;
      width: 0.28rem;
      height: 0.28rem;
    }
    &__tag {
      // 乘以2然后等比例缩小
      position: absolute;
      left: 0.46rem;
      top: 0.04rem;
      padding: 0 0.04rem;
      min-width: 0.2rem;
      height: 0.2rem;
      line-height: 0.2rem;
      text-align: center;
      background-color: $height-light-font-color;
      border-radius: 0.1rem;
      font-size: 0.12rem;
      color: $bg-color;
      transform: scale(0.5);
      transform-origin: left center;
    }
  }
  &__info {
    flex: 1;
    color: $content-font-color;
    font-size: 0.12rem;
    &__price {
      line-height: 0.49rem;
      color: $height-light-font-color;
      font-size: 0.18rem;
    }
  }
  &__btn {
    width: 0.98rem;
    background-color: #4fb0f9;
    text-align: center;
    color: $bg-color;
    font-size: 0.14rem;
    // 去掉a标签的下划线
    a {
      color: $bg-color;
      text-decoration: none; //去掉文本修饰
    }
  }
}
</style>

最终效果如下:


image.png

继续优化一下src\views\shop\Content.vue中的流程代码:

<script>
import { reactive, ref, toRefs, watchEffect } from 'vue'
import { useRoute } from 'vue-router' // 路由跳转方法
import { useStore } from 'vuex'
import { get } from '@/utils/request.js'
import { useCommonCartEffect } from './commnCartEffect'

const categories = [
  {
    name: '全部商品',
    tab: 'all'
  },
  {
    name: '秒杀',
    tab: 'seckill'
  },
  {
    name: '新鲜水果',
    tab: 'fruit'
  },
  {
    name: '休闲食品',
    tab: 'snack'
  }
]

// 和tab切换相关的逻辑
const useTabEffect = () => {
  const currentTab = ref(categories[0].tab)
  const handleTabClick = tab => {
    console.log('click:' + tab)
    currentTab.value = tab
  }
  return { currentTab, handleTabClick }
}
// 当前列表内容相关的函数
const useContentListEffect = (currentTab, shopId) => {
  const content = reactive({ list: [] })
  const getContentData = async () => {
    const result = await get(`/api/shop/${shopId}/products`, {
      tab: currentTab.value
    })
    console.log('result:' + result)
    if (result?.code === 200 && result?.data?.length) {
      content.list = result.data
    }
  }
  // watchEffect:当首次页面加载时,或当其中监听的数据发生变化时执行
  watchEffect(() => {
    getContentData()
  })
  const { list } = toRefs(content)
  return { list }
}

const useCartEffect = shopId => {
  const { cartList, changeCartItemInfo } = useCommonCartEffect()
  const store = useStore()
  const changeShopName = (shopId, shopName) => {
    store.commit('changeShopName', { shopId, shopName })
  }
  const changeCartItem = (shopId, productId, item, num, shopName) => {
    changeCartItemInfo(shopId, productId, item, num)
    changeShopName(shopId, shopName)
  }

  return {
    cartList,
    changeCartItem
  }
}
export default {
  name: 'Content',
  props: {
    id: String,
    shopName: String
  },
  setup() {
    const route = useRoute() // 获取路由

    const shopId = route.params.id
    const { currentTab, handleTabClick } = useTabEffect()
    const { list } = useContentListEffect(currentTab, shopId)
    const { cartList, changeCartItem } = useCartEffect(shopId)
    return {
      cartList,
      list,
      categories,
      handleTabClick,
      currentTab,
      shopId,
      changeCartItem
    }
  }
}
</script>

优化购物车为空时,全选和清空购物车也不显示,修改src\views\shop\Cart.vue:

<template>
  <!-- 蒙层 -->
  <div
    class="mask"
    v-if="showCart && total > 0"
    @click="handleCartShowChange"
  ></div>
  <div class="cart">
    <div class="product" v-show="showCart && total > 0">
......

优化计算属性:

<template>
  <!-- 蒙层 -->
  <div
    class="mask"
    v-if="showCart && calculations.total > 0"
    @click="handleCartShowChange"
  ></div>
  <div class="cart">
    <div class="product" v-show="showCart && calculations.total > 0">
      <div class="product__header">
        <div class="product__header__all" @click="setCartItemsChecked(shopId)">
          <i
            :class="[
              'product__header__all__icon',
              'custom-icon',
              calculations.isAllChecked
                ? 'custom-icon-radio-checked'
                : 'custom-icon-radio-unchecked'
            ]"
          ></i>
          <span class="product__header__all__text">全选</span>
        </div>
        <div class="product__header__clear">
          <span
            class="product__header__clear__btn"
            @click="cleanCartProducts(shopId)"
            >清空购物车</span
          >
        </div>
      </div>
      <template v-for="item in productList" :key="item._id">
        <div class="product__item" v-if="item.count > 0">
          <div
            class="product__item__checked"
            @click="changeCartItemChecked(shopId, item._id)"
          >
            <i
              :class="[
                'custom-icon',
                item.checked == true
                  ? 'custom-icon-radio-checked'
                  : 'custom-icon-radio-unchecked'
              ]"
            ></i>
          </div>
          <img class="product__item__img" :src="item.imgUrl" />
          <div class="product__item__detail">
            <h4 class="product__item__title">{{ item.name }}</h4>
            <p class="product__item__price">
              <span class="product__item__yen"> &yen;{{ item.price }} </span>
              <span class="product__item__origin">
                &yen;{{ item.oldPrice }}
              </span>
            </p>
          </div>
          <div class="product__number">
            <span
              class="product__number__minus"
              @click="
                () => {
                  0
                  changeCartItemInfo(shopId, item._id, item, -1)
                }
              "
              >-</span
            >
            {{ cartList?.[shopId]?.productList.[item._id]?.count || 0 }}
            <span
              class="product__number__plus"
              @click="
                () => {
                  changeCartItemInfo(shopId, item._id, item, 1)
                }
              "
              >+</span
            >
          </div>
        </div>
      </template>
    </div>
    <div class="check">
      <div class="check__icon" @click="handleCartShowChange">
        <img src="/i18n/9_16/img/basket.png" alt="" class="check__icon__img" />
        <div class="check__icon__tag">
          {{ calculations.total }}
        </div>
      </div>
      <div class="check__info">
        总计:<span class="check__info__price"
          >&yen; {{ calculations.totalPrice }}</span
        >
      </div>
      <div class="check__btn">
        <router-link :to="{ name: 'Home' }">
          去结算
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router' // 路由跳转方法
import { useStore } from 'vuex' // 路由跳转方法
import { useCommonCartEffect } from './commonCartEffect'

const useCartEffect = shopId => {
  const store = useStore()
  const { changeCartItemInfo } = useCommonCartEffect()
  const cartList = store.state.cartList // 加入购物车的商品列表

  // 单个勾选或者不勾选
  const changeCartItemChecked = (shopId, productId) => {
    store.commit('changeItemChecked', { shopId, productId })
  }
  // 清除购物车按钮
  const cleanCartProducts = shopId => {
    store.commit('changeCleanCartProducts', { shopId })
  }
  // 购物车全选或者取消全选
  const setCartItemsChecked = shopId => {
    store.commit('setCartItemsChecked', { shopId })
  }

  // 计算shopId下所有cartList的商品数量total、价钱之和totalPrice
  const calculations = computed(() => {
    const productList = cartList[shopId]?.productList
    const resultData = {
      // 总商品数量
      total: 0,
      // 总金额
      totalPrice: 0,
      // 全选
      isAllChecked: true
    }
    debugger
    if (productList) {
      for (const i in productList) {
        const product = productList[i]
        // 总商品数量
        resultData.total += product.count
        // 总金额
        if (product.checked === true) {
          resultData.totalPrice += product.count * product.price
        }
        // 全选
        if (product.count > 0 && !product.checked) {
          resultData.isAllChecked = false
        }
      }
      resultData.totalPrice = resultData.totalPrice.toFixed(2) // 保留2位小数
    }

    return resultData
  })
  // const total = computed(() => {
  //   const productList = cartList[shopId]?.productList
  //   let count = 0
  //   if (productList) {
  //     for (const i in productList) {
  //       const product = productList[i]
  //       count += product.count
  //     }
  //   }
  //   return count
  // })
  // const totalPrice = computed(() => {
  //   const productList = cartList[shopId]?.productList
  //   let count = 0
  //   if (productList) {
  //     for (const i in productList) {
  //       const product = productList[i]
  //       if (product.checked === true) {
  //         count += product.count * product.price
  //       }
  //     }
  //   }
  //   return count.toFixed(2) // 保留2位小数
  // })

  // 全选的计算属性
  // const allChecked = computed(() => {
  //   const productList = cartList[shopId]?.productList
  //   let result = true
  //   if (productList) {
  //     for (const i in productList) {
  //       const product = productList[i]
  //       if (product.count > 0 && !product.checked) {
  //         result = false
  //         break
  //       }
  //     }
  //   }
  //   return result
  // })

  const productList = computed(() => {
    const productInfoList = cartList[shopId]?.productList || [] // 不存在默认空数组
    return productInfoList
  })
  return {
    cartList,
    calculations,
    productList,
    changeCartItemChecked,
    changeCartItemInfo,
    cleanCartProducts,
    setCartItemsChecked
  }
}

// 展示隐藏购物车
const toggleCartEffect = () => {
  const showCart = ref(false)
  // 显示隐藏购物车具体内容
  const handleCartShowChange = () => {
    showCart.value = !showCart.value
  }
  return { showCart, handleCartShowChange }
}
export default {
  name: 'Cart',
  setup() {
    const route = useRoute()
    const shopId = route.params.id // 店铺id
    // 展示隐藏购物车
    const { showCart, handleCartShowChange } = toggleCartEffect()
    // 计算总价和加入购物车的总数量
    const {
      cartList,
      calculations,
      productList,
      changeCartItemChecked,
      changeCartItemInfo,
      cleanCartProducts,
      setCartItemsChecked
    } = useCartEffect(shopId)
    return {
      cartList,
      calculations,
      productList,
      shopId,
      showCart,
      handleCartShowChange,
      changeCartItemChecked,
      changeCartItemInfo,
      cleanCartProducts,
      setCartItemsChecked
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/style/viriables.scss';
@import '@/style/mixins.scss';
.mask {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1;
}
.cart {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
  background: $bg-color;
}
.product {
  overflow-y: scroll;
  flex: 1;
  background: $bg-color;
  &__header {
    display: flex;
    line-height: 0.52rem;
    border-bottom: 0.01rem solid $content-bg-color;
    font-size: 0.14rem;
    color: $content-font-color;
    &__all {
      width: 0.64rem;
      margin-left: 0.18rem;
      &__icon {
        display: inline-block;
        vertical-align: top;
        font-size: 0.2rem;
        margin-right: 0.05rem;
        color: $btn-bg-color;
      }
      &__text {
        display: inline-block;
        margin-left: 0.04rem;
        line-height: 0.52rem;
      }
    }
    &__clear {
      flex: 1;
      text-align: right;
      margin-right: 0.16rem;
      &__btn {
        display: inline-block;
      }
    }
  }
  &__item {
    position: relative;
    display: flex;
    padding: 0.12rem 0.16rem;
    margin: 0 0.16rem;
    border-bottom: 0.01rem solid $content-bg-color;
    &__checked {
      line-height: 0.5rem;
      margin-right: 0.2rem;
      color: $btn-bg-color;
      i {
        font-size: 0.25rem;
      }
    }
    // 配合解决超出长度以省略号显示而不会出现换行
    &__detail {
      overflow: hidden;
    }
    &__img {
      width: 0.46rem;
      height: 0.46rem;
      margin-right: 0.16rem;
    }
    &__title {
      margin: 0;
      line-height: 0.2rem;
      font-size: 0.14rem;
      color: $content-font-color;
      // 超出长度以省略号显示而不会出现换行
      @include ellipsis;
    }
    &__price {
      margin: 0.06rem 0 0 0;
      line-height: 0.2rem;
      font-size: 0.14rem;
      color: $height-light-font-color;
    }
    &__yen {
      font-size: 0.12rem;
    }
    &__origin {
      margin-left: 0.06rem;
      line-height: 0.2rem;
      font-size: 0.12rem;
      color: $light-font-color;
      text-decoration: line-through; //中划线
    }
    // 购物车选购数量和加减号
    .product__number {
      position: absolute;
      right: 0rem;
      bottom: 0.26rem;
      &__minus,
      &__plus {
        display: inline-block;
        width: 0.2rem;
        height: 0.2rem;
        line-height: 0.16rem;
        border-radius: 50%;
        font-size: 0.2rem;
        text-align: center;
      }
      // 边框白色
      &__minus {
        border: 0.01rem solid $medium-font-color;
        color: $medium-font-color;
        margin-right: 0.05rem;
      }
      //无边框,背景蓝色
      &__plus {
        color: $bg-color;
        background: $btn-bg-color;
        margin-left: 0.05rem;
      }
    }
  }
}
.check {
  display: flex;
  box-sizing: border-box; //往内塞入border
  line-height: 0.49rem;
  height: 0.49rem;
  border-top: 0.01rem solid $content-bg-color;
  &__icon {
    width: 0.84rem;
    position: relative;
    &__img {
      margin: 0.12rem auto;
      display: block;
      width: 0.28rem;
      height: 0.28rem;
    }
    &__tag {
      // 乘以2然后等比例缩小
      position: absolute;
      left: 0.46rem;
      top: 0.04rem;
      padding: 0 0.04rem;
      min-width: 0.2rem;
      height: 0.2rem;
      line-height: 0.2rem;
      text-align: center;
      background-color: $height-light-font-color;
      border-radius: 0.1rem;
      font-size: 0.12rem;
      color: $bg-color;
      transform: scale(0.5);
      transform-origin: left center;
    }
  }
  &__info {
    flex: 1;
    color: $content-font-color;
    font-size: 0.12rem;
    &__price {
      line-height: 0.49rem;
      color: $height-light-font-color;
      font-size: 0.18rem;
    }
  }
  &__btn {
    width: 0.98rem;
    background-color: #4fb0f9;
    text-align: center;
    color: $bg-color;
    font-size: 0.14rem;
    // 去掉a标签的下划线
    a {
      color: $bg-color;
      text-decoration: none; //去掉文本修饰
    }
  }
}
</style>

这里还可以将参数封装一下
src\views\shop\Content.vue

......
        <div class="product__number">
          <span
            class="product__number__minus"
            @click="
              () => {
                changeCartItem(shopId, item._id, item, -1, shopName)
              }
            "
            >-</span
          >
          {{ getProductCartCount(shopId, item._id) }}
          <span
            class="product__number__plus"
            @click="
              () => {
                changeCartItem(shopId, item._id, item, 1, shopName)
              }
            "
            >+</span
          >
        </div>
......
<script>
......
const useCartEffect = shopId => {
  const { changeCartItemInfo } = useCommonCartEffect()
  const store = useStore()
  const cartList = store.state.cartList // 加入购物车的商品
......
  const getProductCartCount = (shopId, productId) => {
    return cartList?.[shopId]?.productList?.[productId]?.count || 0
  }
  return {
    cartList,
    changeCartItem,
    getProductCartCount
  }
}
......
</script>
将值存入localstorage

修改src\store\index.js

import { createStore } from 'vuex'

const setLocalStorage = state => {
  const cartList = state.cartList
  const cartListString = JSON.stringify(cartList)
  localStorage.cartList = cartListString
}

export default createStore({
  state: {
    cartList: {
      // shopId: {
      //   shopName: '沃什么码',
      //   productList: {
      //     productId: {
      //       _id: '1',
      //       name: '番茄250g/份',
      //       imgUrl: '/i18n/9_16/img/tomato.png',
      //       sales: 10,
      //       price: 33.6,
      //       oldPrice: 39.6,
      //       count: 0
      //     }
      //   }
      // }
      // ================== 之前版本的结构 ==================
      // 第一层级:商铺的id
      // 第二层内容是商品内容以及购物数量
      // shopId: {
      //   productID: {
      //     _id: '1',
      //     name: '番茄250g/份',
      //     imgUrl: '/i18n/9_16/img/tomato.png',
      //     sales: 10,
      //     price: 33.6,
      //     oldPrice: 39.6,
      //     count: 0
      //   }
      // }
    }
  },
  mutations: {
    /**
     * 加入或减少购物车数量
     * @param {*} state
     * @param {String} shopId 店铺id
     * @param {String} productId 商品id
     * @param {Object} productInfo 商品信息集
     * @param {Number} num 加入购物车的数量
     * @param {*} payload
     */
    changeItemToCart(state, payload) {
      const { shopId, productId, productInfo, num } = payload
      // console.log(shopId, productId, productInfo)
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }

      let product = shopInfo?.productList[productId]
      if (!product) {
        productInfo.count = 0
        product = productInfo // 初始化
      }

      product.count += num
      // && 短路运算符,前面的满足才会执行后面的逻辑,等价于if
      num > 0 && (product.checked = true)

      product.count <= 0 && (shopInfo[productId].count = 0)
      // delete state.cartList[shopId]

      shopInfo.productList[productId] = product
      // 赋值
      state.cartList[shopId] = shopInfo
      setLocalStorage(state)
    },
    // 购物车勾选记录
    changeItemChecked(state, payload) {
      const { shopId, productId } = payload
      const product = state.cartList[shopId].productList[productId]
      product.checked = !product.checked
      setLocalStorage(state)
    },
    // 清除购物车
    changeCleanCartProducts(state, payload) {
      const { shopId } = payload
      state.cartList[shopId].productList = {}
      setLocalStorage(state)
    },
    // 购物车全选或者取消全选
    setCartItemsChecked(state, payload) {
      const { shopId } = payload
      const products = state.cartList[shopId].productList
      if (products) {
        for (const i in products) {
          const product = products[i]
          product.checked = true
        }
      }
      setLocalStorage(state)
    },
    /**
     * 修改商店名称
     * @param {Object} state vuex对象
     * @param {Object} payload 传值
     */
    changeShopName(state, payload) {
      const { shopId, shopName } = payload
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
    }
  },
  actions: {},
  modules: {}
})

image.png

完善读取:

import { createStore } from 'vuex'

/**
 * 存入localStorage
 * @param {Object} state
 */
const setLocalCartList = state => {
  const cartList = state.cartList
  const cartListString = JSON.stringify(cartList)
  localStorage.cartList = cartListString
}

/**
 * 从localStorage读取
 * @param {Object} state
 */
const getLocalCartList = () => {
  return JSON.parse(localStorage.cartList) || {}
}

export default createStore({
  state: {
    cartList: getLocalCartList()
......

这样刷新也能看到数据回显。

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):