如何将数据“加载”到Vue组件中?

时间:2020-09-15 19:32:53

标签: vue.js vuejs2 vue-component

试图把头放在组件周围,我很难将官方的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,我在指令中没有正确引用它吗?

1 个答案:

答案 0 :(得分:2)

您应该从您的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