亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

vue 組件不渲染從后端獲取的數據

vue 組件不渲染從后端獲取的數據

千萬里不及你 2023-07-20 15:00:16
我有一個非?;镜?HTML 頁面,其中有一個簡單的 Vue 組件。在網絡選項卡中,我可以看到它正確獲取了數據,應該出現的列表已呈現,但數據根本不存在。    <div id="app">      <h2>Total inventory: {{ totalProducts }}</h2>      <ul>        <li>beginning of the list</li>        <li v-for="product in products">          {{ product.name }} {{ product.price }}        </li>        <li>End of the list</li>      </ul>    </div>    <script src="https://unpkg.com/vue"></script>    <script>      const app = new Vue({        el: '#app',        data: {          products: []        },        created () {          fetch('http://localhost:3000/api/teddies')            .then(response => response.json())            .then(json => {              this.products = json.products            })        },        computed () {          return this.products.reduce((sum, product) => {            return sum + product.quantity          }, 0)        }      })    </script>我嘗試將腳本的代碼包含到一個單獨的文件中,使用 axios 進行請求(我知道它不會改變任何事情,因為請求實際上已經有效),將 ID 直接歸因于列表并在腳本中使用它...沒有出現任何內容來代替 {{ Product.name }} 和 {{ Product.price }} 。同樣適用于totalProducts變量和{{totalProducts}}
查看完整描述

2 回答

?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

json直接分配給this.productslike :


 fetch('https://fakestoreapi.com/products')

            .then(response => response.json())

            .then(json => {

              this.products = json           

            })

因為json代表products列表,所以json.products會返回undefined


計算屬性應定義如下:


computed:{

  comp1(){...},

 comp2(){...}

}

<div id="app">

  <h2>Total inventory: {{ totalProducts }}</h2>

  <ul>

    <li>beginning of the list</li>

    <li v-for="product in products">

      {{ product.title }} {{ product.price }}

    </li>

    <li>End of the list</li>

  </ul>

</div>

<script src="https://unpkg.com/vue"></script>

<script>

  const app = new Vue({

    el: '#app',

    data: {


      products: []


    },

    created() {

      fetch('https://fakestoreapi.com/products')

        .then(response => response.json())

        .then(prod => {


          this.products = prod

         

        })

    },

    computed: {

      totalProducts() {

        return this.products.reduce((sum, product) => {

          return sum + product.price

        }, 0)

      }

    }


  })

</script>


查看完整回答
反對 回復 2023-07-20
?
慕姐4208626

TA貢獻1852條經驗 獲得超7個贊

您的數據應該返回一個返回新對象的函數:


短途


data: () => ({

   products: []

})

很長的路要走


data() {

  return {

    products: []

  }

}


查看完整回答
反對 回復 2023-07-20
  • 2 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號