vue-cookies 获取值返回对象而不是实际值
P粉878510551
P粉878510551 2024-01-01 13:57:08
0
2
485

我在我的 vue 项目中使用 vue-cookies npm 包。我安装包、在项目中初始化它并设置 cookie 没有问题。但是,当我尝试通过键检索存储在 cookie 中的值时,它没有显示我存储的值,而是显示 [object Object],我不确定出了什么问题: 这是我的代码:

this.cart.push({
  productID: this.product._id,
  product: {
    productName: this.product.productName,
    thumbnail: this.product.productMedia[0].imagePath,
    option: 'Digital Download'
  },
  unitPrice: this.product.price.listingPrice,
  quantity: 1
})
console.log(this.cart)
this.$cookies.set('cart', this.cart, 60 * 60 * 24)
console.log(this.$cookies.isKey('cart'))
console.log(this.$cookies.get('cart'))

我确定 this.cart 不为空, $this.$cookies.isKey('cart) 返回 true,但是 $cookies.get() 方法返回 [ object Object]而不是我存储的购物车值。如有任何帮助,我们将不胜感激!

P粉878510551
P粉878510551

全部回复(2)
P粉447785031

如果您想在控制台中查看该值,请尝试执行以下操作

console.log(JSON.stringify(this.$cookies.get('cart')))

有问题的对象可能是嵌套的,这就是它无法打印的原因。

P粉810050669

在cookie中设置JSON对象时。您可以将键值设置为 JSON 字符串,而不是 JSON 对象。

this.$cookies.set('cart', JSON.stringify(this.cart), 60 * 60 * 24)

获取时可以通过将JSON字符串解析为对象来访问。

JSON.parse(this.$cookies.get('cart'))
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!