【问题标题】:How to 'load' data into a Vue component?如何将数据“加载”到 Vue 组件中?
【发布时间】:2020-09-15 19:32:53
【问题描述】:

试图将我的头脑围绕在组件上,我很难将官方的 vuejs.org 指南示例(主要使用 new Vue({...}))翻译成由 CLI 生成的全新 Vue 应用程序提供的模块结构。

如果我有类似的东西

const products = {
  'bat': '9.99',
  'glove': '7.50',
  'cleets': '12.50'
}

如何将其“加载”到组件中?

Products.vue

<template>
  <div>
    <li v-for="product in products">
      {{ product }}
    </li>
  </div>
</template>

<script>
  export default {
    name: 'Products',
    data: function () {
      products: ??   // <-- My understanding is the products data would be added here somehow?
    }
  }
</script>

然后,在“Home.vue”组件中,类似

<template>
   <div>
      <Products />
  </div>
</template>

<script>
  import Products from "@/components/Products.vue";

  export default {
    name: "Home",
    components: {
      Products,
    },
  };
</script>

有什么建议吗?谢谢你的帮助!很抱歉,如果它应该是显而易见的,那么无法弄清楚 Vue.js 的一个相当基本的概念是令人沮丧的 :(


根据@A.khalifa 的回复,我将Products.vue 修改为以下内容

<script>
export default {
  name: 'Products',
  data: function() {
    products: [{
      'bat': '9.99',
      'glove': '7.50',
      'cleets': '12.50'
    }]
  }
}
</script>

现在返回以下错误

10:5  error  Elements in iteration expect to have 'v-bind:key' directives  vue/require-v-for-key
23:5  error  'products:' is defined but never used                           no-unused-labels

我不确定如何处理 v-bind:key 指令...至于 products 我在指令中没有正确引用它吗?

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    你应该从你的data返回一个对象

    data: function () {
        return {
            products: {
              'bat': '9.99',
              'glove': '7.50',
              'cleets': '12.50'
            }
        }
    }
    

    data() {
        return {
            products: {
              'bat': '9.99',
              'glove': '7.50',
              'cleets': '12.50'
            }
        }
    }
    

    在你的模板上

    <li v-for="(price, name) in products" :key="name">
        {{ name }} = {{ price }}
    </li>
    

    在此处阅读有关基本组件的更多信息:https://vuejs.org/v2/guide/components.html#Base-Example

    并在此处使用 v-for 与对象:https://vuejs.org/v2/guide/list.html#v-for-with-an-Object

    【讨论】:

    • 啊,是的!你说得对,我忘了return 的事情。非常感谢@Owl!对于输出来说,它也像一个魅力:)
    猜你喜欢
    • 1970-01-01
    • 2021-05-23
    • 2021-11-02
    • 2019-06-13
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    相关资源
    最近更新 更多