
知识点 : query:查询字符串
分析需求:我们需要在商品页点击具体商品的时候,获取当前商品信息,才能够跳转到具体的商品页面 :所以可以用查询字符串获取当前的信息,就会拼接到地址栏上。
query:{itemId:item.sku_info[itemIndex].sku_id,地址栏会显示 : /item?itemId=100027101,问号后面的就是查询字符串。

1. 组件:商品页
商品页中 : 点击商品详情或者商品按钮,跳转到商品详情组件中。
<div class="item-cover">
<router-link
//此处知识点query查询字符串,拼接商品id
//此时地址栏的显示:http://localhost:8080/item?itemId=100027101
:to='{name:"Item",query:{itemId:item.sku_info[itemIndex].sku_id}}'>
</router-link>
</div>
2. 组件:views,即商品详情页,如何获取传递过来的query数据?
2-1 : 首先在商品详情页引入数据 :
import itemsData from '@/lib/newItemsData'
data() {
return {
itemsData, //将数据挂载
itemId : this.$route.query.itemId
}
}
2-2 : 通过对比itemsData和itemId(即传过来的query),相同即可输出对应的数据。然后绑定到页面上。
computed: {
itemInfo() {
let itemInfo = this.itemsData.filter((item) => {
return Number(item.sku_id) === Number(this.itemId) //return出来的是一个数组
})[0]
console.log(itemInfo)
return itemInfo
}
}
2-3 :商品左侧图片切换

这类切换需求,都是统一的设置一个index变量,绑定点击事件的时候获取当前的index,然后改变index即可。
data() {
return {
imgIndex: 0
}
},
methods: {
tableImg(index){
this.imgIndex = index
}
}
======
<li
:class="{'on':index==imgIndex}" //判断imgIndex来控制显示隐藏或切换cur
@click="tableImg(index)"
>
</li>
2-4 :商品切换

实际上就是重新渲染这个组件,所以这几个切换颜色的按钮需要时router-link,在点击的时候获取$route.query.id,因为这个页面已经是对应的商品了,现在是切换对应商品里面的不同商品颜色(可以看数据结构就明白了)。但是查询字符串的ID一开始就已经是确认了,如何响应它的变化?就用到了watch来监控,让当前的查询字符串等于router-link上传递的查询字符串,即可对应到此条数据。
总结:此页面是通过查询字符串的ID来改变的,所以要实时获取这个ID,用watch监控。
<router-link
:to="{name:'Item',query:{itemId:color.id}}"
:title="color.color"
>
<img :src="'http://img01.smartisanos.cn/'+color.image+'20X20.jpg'">
</router-link>
watch : {
//当查询字符串改变的时候,将当前的值重新赋值
'$route.query.itemId'(){
this.itemId = this.$route.query.itemId
this.imgIndex = 0
}
}
2-5 加入购物车
直接调用vuex中写好的方法即可
// 点击加入购物车,直接用详情页写好的即可,这里不是data,传递的是过滤好的itemInfo
addCarPanelHandel(){
let itemData = {
info : this.itemInfo,
count : this.count //为的是用户加了几件就计算几件
}
this.$store.commit('addCarPanelData',itemData)
}
2-6 超出最大值显示弹窗
<prompt></prompt>
// 弹窗
import prompt from '@/components/prompt'
components: {
prompt
}
总结
通过学习,我记住了一点:就会这类数据终将是要加入到购物车的,那么就是都操作的是vuex里的数据,添加购物车已经在vuex中写好,所以这里只需要去commit相应的mutation即可。
还学习到一点:可以传递对象。
addCarPanelHandel(){
let itemData = {
info : this.itemInfo, //当前添加的数据
count : this.count //数量
}
this.$store.commit('addCarPanelData',itemData)
}
网友评论