首頁  >  問答  >  主體

模板無法捕捉到計算屬性的內容,但生命週期鉤子可以正常記錄

<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>
P粉604669414P粉604669414415 天前510

全部回覆(1)我來回復

  • P粉665679053

    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
      }
    },
    

    回覆
    0
  • 取消回覆