【问题标题】:VueJs data binding issueVueJs 数据绑定问题
【发布时间】:2017-02-16 07:04:03
【问题描述】:

我尝试将属性和一些数据绑定到我的模板,但下面的代码不起作用。我需要的是渲染 n 数量的模板取决于 printForms 对象的数量,并在每个模板数据中从适当的对象中实现。 请提供任何想法我的代码有什么问题。

附:我在控制台中警告如下: [Vue 警告]:评估表达式“printedForm.docNumber”时出错:TypeError:无法读取未定义的属性“docNumber”(在组件中找到:)

 <div id="app">
  <printing-form v-for="printedForm in printedForms" track-by="id"></printing-form>
 </div>

 <template id="printingForm-template">
   <img v-bind="printedForm.attributes">
   <div>{{ printedForm.docNumber }}</div>
 </template>

我的 VueJs 代码如下:

Vue.component('printing-form', {
  template: '#printingForm-template'
});

new Vue({
  el: '#app',
  data: {
    printedForms: [
      {
        id: 1,
        docNumber: 7,
        attributes: {
          src: '/waybill/img/4p_bus.png',
          width: 1400,
          height: 980
        }
      },
      {
        id: 2,
        docNumber: 7777,
        attributes: {
          src: '/waybill/img/4p_cargo.png',
          width: 1400,
          height: 980
        }
      },
      {
        id: 3,
        docNumber: 10000,
        attributes: {
          src: '/waybill/img/4p_selfMove.png',
          width: 1400,
          height: 980
        }
      }
    ]
  }
});

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    您需要像这样绑定printedForm 属性:printed-form="printedForm"

    <printing-form v-for="printedForm in printedForms" 
    track-by="id" :printed-form="printedForm"></printing-form>
    

    并在组件props中定义

    Vue.component('printing-form', {
      template: '#printingForm-template',
      props: ['printedForm']
    });
    

    Vue props

    注意当使用 camelCased 道具名称作为属性时,您需要使用它们的 kebab-case(连字符分隔)等价物

    Vue Docs

    【讨论】:

    • 打败我,所以我不会发布我的答案。我要提到的另一件事虽然与问题无关,但组件的模板应该有一个根元素。
    • 不,它不应该,这取决于你在做什么,我做了那个例子检查它vue exmple
    • 是的,应该。在 Vue 2 中它是必需的。在 Vue 1 中,您最终会得到片段实例和性能成本。 v1.vuejs.org/guide/components.html#Fragment-Instance
    • @BillCriswell 你是对的,我在 Vue 1.x 的迁移中发现了这一点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 2016-10-02
    相关资源
    最近更新 更多