Vue.js-无法访问道具对象的属性

时间:2018-08-09 17:45:14

标签: vue.js

我正在创建,然后使用pdfjs将对象传递给子Vue组件。这样做时,我可以访问对象本身,但是不能访问对象的任何属性。

在所有生命周期挂钩期间都是这种情况。

<i-slide-deck-pdf // calling child vue component
    v-if="true"
    :slideDeckItem="fetchPDF('/static/intropdf.pdf')"
    :current-user-progress="currentUserProgress"
    @i-progress="putProgressTracker"
    @i-slide-change="onSlideChange"
/>

...

fetchPDF(url) { // function being used to create the object
  let pdfItem = new Object();
  import(
    'pdfjs-dist/webpack'
  ).
    then(pdfjs => pdfjs.getDocument(url)).
    then(pdf => {
      pdfItem.pdf = pdf;
      pdfItem.pages = range(1, pdf.numPages).map(number => pdf.getPage(number));
      pdfItem.pageCount = pdfItem.pages.length;
    })
  return pdfItem;
},

...

props: { // prop call in child component
  slideDeckItem: {
    type: Object,
    required: true
  },
}

Console log

预先感谢。

1 个答案:

答案 0 :(得分:0)

这是因为异步调用尚未完成,因此您只是返回一个空对象,要解决此问题,您需要在代码的then部分中设置一个值,并将其绑定到prop ,所以:

fetchPDF(url) { // function being used to create the object
  let pdfItem = new Object();
  import(
    'pdfjs-dist/webpack'
  ).
    then(pdfjs => pdfjs.getDocument(url)).
    then(pdf => {
      pdfItem.pdf = pdf;
      pdfItem.pages = range(1, pdf.numPages).map(number => pdf.getPage(number));
      pdfItem.pageCount = pdfItem.pages.length;

      // This should be inside the "then"
      this.slideDeckItem = pdfItem; 
    })
},

然后,您想在父数据属性中声明slideDeckItem,并将其绑定到组件的prop:

<i-slide-deck-pdf
    v-if="true"
    :slideDeckItem="slideDeckItem"
    :current-user-progress="currentUserProgress"
    @i-progress="putProgressTracker"
    @i-slide-change="onSlideChange"
/>

尽管我已经使用超时来模拟异步调用:http://jsfiddle.net/ga1o4k5c/

,但我制作了一个JSFiddle,为您提供基本概念。

您可能还想看看how Promises work