vue 组件不渲染从后端获取的数据

我有一个非常基本的 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}}


千万里不及你
浏览 136回答 2
2回答

RISEBY

json直接分配给this.productslike :&nbsp;fetch('https://fakestoreapi.com/products')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(response => response.json())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(json => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.products = json&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })因为json代表products列表,所以json.products会返回undefined计算属性应定义如下:computed:{&nbsp; comp1(){...},&nbsp;comp2(){...}}<div id="app">&nbsp; <h2>Total inventory: {{ totalProducts }}</h2>&nbsp; <ul>&nbsp; &nbsp; <li>beginning of the list</li>&nbsp; &nbsp; <li v-for="product in products">&nbsp; &nbsp; &nbsp; {{ product.title }} {{ product.price }}&nbsp; &nbsp; </li>&nbsp; &nbsp; <li>End of the list</li>&nbsp; </ul></div><script src="https://unpkg.com/vue"></script><script>&nbsp; const app = new Vue({&nbsp; &nbsp; el: '#app',&nbsp; &nbsp; data: {&nbsp; &nbsp; &nbsp; products: []&nbsp; &nbsp; },&nbsp; &nbsp; created() {&nbsp; &nbsp; &nbsp; fetch('https://fakestoreapi.com/products')&nbsp; &nbsp; &nbsp; &nbsp; .then(response => response.json())&nbsp; &nbsp; &nbsp; &nbsp; .then(prod => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.products = prod&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; },&nbsp; &nbsp; computed: {&nbsp; &nbsp; &nbsp; totalProducts() {&nbsp; &nbsp; &nbsp; &nbsp; return this.products.reduce((sum, product) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return sum + product.price&nbsp; &nbsp; &nbsp; &nbsp; }, 0)&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; })</script>

慕姐4208626

您的数据应该返回一个返回新对象的函数:短途data: () => ({&nbsp; &nbsp;products: []})很长的路要走data() {&nbsp; return {&nbsp; &nbsp; products: []&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript