1.首先简单封装一个localStorage()方法:
const storage
= {
set(key
, value
){
localStorage
.setItem(key
,JSON.stringify(value
))
},
get(key
){
return JSON.parse(localStorage
.getItem(key
)||'[]')
},
remove(){
localStorage
.removeItem(key
)
}
}
export default storage
2.在vuex的store文件中引入,下面就能够使用了
import localStore
from '../storage/index.js'
3.将组件中传给store的数据存入localStorage中
在加入购物车组件中传给store商品信息
this.$store
.commit("add",obj
)
store接收
state
: {
storeLs
: localStore
.get('list') || ''
},
add (state
, obj
) {
let arrLs
= state
.storeLs
.find(v
=> v
.info
.id
=== obj
.info
.id
)
if (arrLs
) {
arrLs
.num
+= obj
.num
} else {
state
.storeLs
.push(obj
)
}
localStore
.set('list', state
.storeLs
)
}
4.购物车页面渲染
computed
: {
shopList(){
return this.$store
.state
.storeLs
}
}
5.如果想要存贮,多选框的状态,加减后的数量等,需要深度监听vuex里的数据
watch
: {
shopList
:{
handler(){
localStore
.set("list",this.shopList
)
},
deep
:true
}
}
-------------*勤学如春起之苗,不见其增,日有所长*
转载请注明原文地址: https://mac.8miu.com/read-500484.html