模板无法捕捉到计算属性的内容,但生命周期钩子可以正常记录
                
             
            
            
                <p>我正在创建一个网店,在这里您可以选择在不干扰购物车内容的情况下订购产品。我实现的方式是共享一个页面,用于购物车项目和单个产品。它会检查是否设置了productID参数,如果是,则使用不同的数据。</p>
<p>这是我编写的函数:</p>
<pre class="brush:js;toolbar:false;">    computed : {
        products: function() {
            if ( this.$route.query.pid ) {
                var product = [{}]
                axios.get(`/api/products/${this.pid}`).then(response => {
                    product[0].id = response.data[0].id
                    product[0].name = response.data[0].name
                    product[0].units = response.data[0].units
                    product[0].image = response.data[0].product_image[0].image
                    product[0].price = response.data[0].price
                    product[0].quantity = 1
                })
                return Object.assign(product)
            } else {
                return this.$store.state.cart
            }
        }
    },
</pre>
<p>这是成功获取数据的生命周期钩子(beforeMount):</p>
<pre class="brush:js;toolbar:false;">    beforeMount() {
        console.log(this.products)
    }
</pre>
<p>现在的问题是,模板中将products属性视为空。当我不带查询参数访问该页面时,一切正常,只是无法找到单个产品的计算数据。</p>
<p>如何解决这个问题?提前感谢您的帮助!</p>            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
         
        
        
     
vue/no-async-in-computed-properties
属性在模板中没有被捕获,但生命周期钩子可以通过计算属性获取数据
你在控制台中看到的原因是因为大多数现代浏览器将对象作为实时数据记录(一旦对象更新,控制台也会更新)。所以你在控制台中看到的不是
console.log执行时对象的值,而是稍后的值。你可以通过使用console.log(JSON.parse(JSON.stringify(this.products)))来确认这一点...为了解决这个问题,使用
watch而不是computeddata() { 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 } },