获取父组件中的数据集

时间:2018-03-12 11:29:12

标签: vue.js vue-component vue-router

我使用Vue CLI生成Vue应用程序。它创建了两个组件AppHelloWorld

在我的应用程序组件中,我立即开始调用一个thide派对服务,以便为其他组件的调用设置一些东西(比如获取令牌)。但是,我想将App.vue组件内的数据共享给它的所有子组件,因为它是应用程序的模板。

我怎样才能做到这一点?在这里思考的正确方法是什么?我应该编写某种存储我想要的特定数据的服务,以便从所有其他组件访问该服务吗?

这是我在App.vue中访问令牌的方式:

methods: {
    fetchToken: function () {
      const url = this.baseUrl + this.tokenUrl
      fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + this.subKey
        }
      })
        .then(res => res.json())
        .then(json => {
          console.log('Getting token..', json.data)
          this.token = json.data
          this.token.created = new Date()
        })
    }
  },


<template>
  <div id="app">
    <router-view/>
  </div>
</template>

这是模板代码在App.vue中的外观,因为我使用Vue-router,它在索引页面上显示正确的组件。

App.vue我可以简单地this.token来访问数据,但在其他组件中我当然得到: Property or method "token" is not defined on the instance,因为该组件中没有定义该属性。

提前致谢。

0 个答案:

没有答案