侦听综合运用

Watch

实验题目
购物车
实验目的
掌握侦听器 Watch 和自动侦听器 watchEffect 的基本使用
熟悉生命周期函数 Lifecycle 的不同阶段和使用
进一步理解 Vue 的响应式数据
进一步熟悉事件 Event 和事件修饰符 Modifier 的使用
实验内容
数据的加载和渲染
商品数量的增加和减少
使用侦听处理业务

. 全选

. 部分选择

. 结算

参考效果和参考代码
静态页面设计与实现
数据设计

. 待选商品 lists:数组;本地数据或使用 fetch 或 axios加载远程数据

. 选中商品 selectedLists;数组

. 是否全选 isAll,布尔;默认是真,全选

. 商品数量总数 count;数值

. 商品价格总数 totalPrice;数值

. 商品折扣价格总数 discountPrice;数值

import { useCartStore } from '@/stores/cart';
const cartStore = useCartStore();
const lists = ref([])
const selectedLists = ref([])
const isAll = ref(false)
const totalPrice = ref(0)
const discountPrice = ref(0)
const count = ref(0)

onMounted(() => {
  lists.value = cartStore.lists;
  selectedLists.value = [...lists.value]
})
渲染数据

. 列表渲染多个商品项

商品的选择侦听

. 每个商品项的选择和 selectedLists 使用双向绑定

<div v-for="(cart, ind) in lists">
  <input type="checkbox" name="cart" v-model="selectedLists" :value="cart">
  // .商品信息,可以封装为组件
</div>

. 侦听 selectedLists:如果选中列表长度和商品列表长度相等,则全选为真;否则全选为假

. 其它业务

watch(selectedLists, (newVal) => {
  isAll.value = newVal.length == lists.value.length
  
  // 总价结算 totalPrice
  
  // 数量结算 count

  // 折扣 discountPrice
}, { deep: true, immediate: true })
商品的数量增加/减少

. 单击商品项的增加和减少按钮相应的调整其数量;并根据库存进行越界检测

. 这里使用内联事件方式;也可以使用函数方式

<button class="btn" @click="cart.quantity--" :disabled="cart.quantity <= 1">-</button>
<button class="btn" @click="cart.quantity++" :disabled="cart.quantity >= cart.stock">+</button>
全选侦听

. 双向绑定 isAll

. 使用改变事件,判断是全选还是全不选

<input type="checkbox" name="all" v-model="isAll" @change="selectAllChange"/>all
const selectAllChange = () => {
  if (isAll.value) {
    selectedLists.value = [...lists.value]
  } else {
    selectedLists.value = []
  }
}
总价结算

. 确保侦听为深度侦听和立即侦听:便于页面渲染完毕时立即更新数据;或使用自动侦听 watchEffect

totalPrice.value = selectedLists.value.reduce((total, item) => total + item.quantity * item.price * (1 - item.discount), 0).toFixed(2)
数量结算
count.value = selectedLists.value.reduce((total, item) => total + item.quantity, 0)
折扣结算
discountPrice.value = selectedLists.value.reduce((total, item) => total + item.quantity * item.price * item.discount, 0).toFixed(2)
购物车静态页面
购物车侦听1 - 自动全选并结算
购物车侦听2 - 全选、增加商品数量
购物车侦听3 - 部分选择
更多功能及效果

. 按数量排序

const isAscending = ref(true)

const sortQuantity = () => {
  isAscending.value = !isAscending.value
  return lists.value.sort((a, b) => isAscending.value ? a.price - b.price : b.price - a.price)
}

. 按字母排序

const islocaleCompare = ref(true)

const sortTitle = () => {
  islocaleCompare.value = !islocaleCompare.value
  return lists.value.sort((a, b) => islocaleCompare.value ? a.title.localeCompare(b.title) : b.title.localeCompare(a.title))
}
默认显示
字母排序 - 降序
字母排序 - 升序
数字排序 - 降序
数字排序 - 升序
拓展与思考
封装商品项为组件
使用 Axios 处理数据
增加排序:商品名称、价格、库存等字段的升序、降序
保存/推送项目到自己的代码仓库