P粉6656790532023-08-31 11:46:54
vue/no-async-in-computed-properties
#屬性在模板中沒有被捕獲,但生命週期鉤子可以透過計算屬性來取得資料
#你在控制台中看到的原因是因為大多數現代瀏覽器將物件作為即時資料記錄(一旦物件更新,控制台也會更新)。所以你在控制台中看到的不是console.log
執行時物件的值,而是稍後的值。你可以透過使用console.log(JSON.parse(JSON.stringify(this.products)))
來確認這一點...
為了解決這個問題,使用watch
而不是computed
data() { return { products: [] } }, watch: { '$route.query.pid': { handler: function(newValue) { if(newValue) { axios.get(`/api/products/${newValue}`).then(response => { var product = { id: response.data[0].id, name: response.data[0].name, units: response.data[0].units image: response.data[0].product_image[0].image price: response.data[0].price quantity: 1 } this.products = [] this.products.push(product) } else this.products = this.$store.state.cart }, immediate: true } },