首頁  >  問答  >  主體

vue-cookies 取得值回傳物件而非實際值

我在我的 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粉878510551P粉878510551292 天前497

全部回覆(2)我來回復

  • P粉447785031

    P粉4477850312024-01-02 10:37:36

    如果您想在控制台中查看該值,請嘗試執行以下操作

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

    有問題的物件可能是嵌套的,這就是它無法列印的原因。

    回覆
    0
  • P粉810050669

    P粉8100506692024-01-02 10:05:01

    在cookie中設定JSON物件時。您可以將鍵值設為 JSON 字串,而不是 JSON 物件。

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

    取得時可以透過將JSON字串解析為物件來存取。

    JSON.parse(this.$cookies.get('cart'))

    回覆
    0
  • 取消回覆