The template cannot capture the contents of the calculated property, but the life cycle hook can record it normally
P粉604669414
P粉604669414 2023-08-30 23:44:38
0
1
580
<p>I'm creating an online store where you can choose to order products without interfering with the contents of your shopping cart. The way I implement it is to share a page for cart items and individual products. It checks if the productID parameter is set and if so, uses different data. </p> <p>This is the function I wrote: </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>This is the life cycle hook (beforeMount) that successfully obtains data: </p> <pre class="brush:js;toolbar:false;"> beforeMount() { console.log(this.products) } </pre> <p>The problem now is that the products attribute is considered empty in the template. When I access the page without query parameters, everything works fine, I just can't find the calculated data for the individual products. </p> <p>How to solve this problem? Thanks in advance for your help! </p>
P粉604669414
P粉604669414

reply all(1)
P粉665679053

vue/no-async-in-computed-properties

Properties are not captured in templates, but lifecycle hooks can obtain data through calculated properties

The reason you see that in the console is because most modern browsers log objects as live data (once the object is updated, the console is updated too). So what you see in the console is not the value of the object when console.log is executed, but the value later. You can confirm this by using console.log(JSON.parse(JSON.stringify(this.products)))...

To solve this problem, use watch instead of 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
  }
},
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template