将数据从实例化传递到Vue组件

时间:2017-09-28 06:56:15

标签: vue.js

我们说我有一个Vue组件:

<item v-bind:orangeFruit ></item>

我想从我的Vue实例中传递一些计算属性:

var fruits = {
  fruit1:'apple',
  fruit2:'orange',
  fruit3:'strawberry'
}

new Vue({
  el: '#app',
  data: {
    return fruits
  },
  computed: {
    orangeFruit: function(){
      // Assume this is much more complicated than just fetching a key
      return this.fruit2;
    }
  }

})

然后,我做了类似的事情:

Vue.component('item,
   template:`

     // This should fetch the computed property from instantiation
     <p>{{ orangeFruit }}</p> `,

   props: {
     orangeFruit
   }
)

但这会导致orangeFruit undefined错误。

1 个答案:

答案 0 :(得分:1)

试试这个:

<item v-bind:orangeFruit ></item>

应该是:

<item :orangeFruit="orangeFruit"></item>

您的代码应如下所示:

new Vue({
  el: '#app',
  data: {
    fruits : fruits 
  },
  computed: {
    orangeFruit: function(){
      // Assume this is much more complicated than just fetching a key
      return this.fruits.fruit2;
    }
  }

})