1.退出登陆 规定从 'login'跳转过来的就当前页面重新获取购物车数量
logout () {
this.axios.post('/user/logout').then(() => {
this.$message.success('退出成功')
this.$cookies.set('userId', '', '-1')
this.$store.dispatch('saveUserName', '')
this.$store.dispatch('saveCartCount', '0')
})
}
mounted () {
this.getProductList()
// router 路由 route当前路由的实例
const params = this.$route.params
if (params && params.from === 'login') {
this.getCartCount()
}
}
2.在登录页面‘login’ login.vue 将cookie 设置为session级别的 关闭浏览器cookie消失
login () {
const { username, password } = this
if (!username || !password) {
this.$message.error('请输入正确的用户名和密码')
return
}
this.axios.post('/user/login', {
username,
password
}).then((res) => {
this.$cookies.set('userId', res.id, 'Session')
this.$store.dispatch('saveUserName', res.username)
//指定跳转
this.$router.push({
name: 'index',
params: {
from: 'login'
}
})
},
getCartCount () {
this.axios.get('/carts/products/sum').then((res = 0) => {
// to-do 保存到vuex里面
this.$store.dispatch('saveCartCount', res)
})
}
------------------
在app.vue中判断是否登录 获取用户信息和购物车数据
mounted () {
const isCookie = this.$cookies.get('userId')
if (isCookie) {
this.getUser()
this.getCartCount()
}
}
---------------------
如果在主页面有添加购物车的功能则要
addCart (id) {
const isCookie = this.$cookies.get('userId')
if (!isCookie) {
this.$message.warning('你还没有登录')
setTimeout(() => {
window.location.href = '/#/login'
}, 2000)
return
}
this.axios.post('/carts', {
productId: id,
selected: true
}).then((res) => {
this.showModal = true
this.$store.dispatch('saveCartCount', res.cartTotalQuantity)
}).catch(() => {
this.showModal = true
})
}