使用 Gridsome 访问来自 Vue 组件的查询数据

Sub*_*dli 6 static-pages vue.js graphql gridsome

我是 Gridsome 和 GraphQL 的新手。但是我没有在这个项目中使用 GraphQL。我只有一个 Gridsome 项目设置和一些 JSON 数据,我正在尝试全局定义它,以便我可以从我的所有 Vue 页面和组件访问它。(我知道它可以导入到组件中,但我正在寻找更多的“Gridsome 方式”来做到这一点)。我已经完成了以下步骤来实现这一目标:

1) 为 Json 文件创建一个文件夹:data/myJson.json. json文件:

{
    "startPage": {
        "title": "Welcher Typ bist Du?",
        "subtitle": "Los geht's beim lustigen Datev-Quiz!",
        "startButton": "Quiz starten"
    }
}
Run Code Online (Sandbox Code Playgroud)

2)我gridsome.server.js的看起来像这样:

var myJson = require('./data/questions.json');
module.exports = function (api) {
  api.loadSource(store => {
    const startPage = store.addContentType({
      typeName: 'StartPage'
    });

    startPage.addNode({
      title: 'StartPageInfo',
      fields: {
        title: myJson.startPage.title,
        subtitle: myJson.startPage.subtitle,
        startButton: myJson.startPage.startButton
      }
    })
  })
}
Run Code Online (Sandbox Code Playgroud)

3)我在index.vue页面中查询这些数据。

我可以在我的模板中访问这些数据。所以如果我做这样的事情

<h4 v-html="$page.allStartPage.edges[0].node.fields"></h4>
Run Code Online (Sandbox Code Playgroud)

然后它工作得很好。

然而,我的问题是,我无法在 Vue 的data对象或方法等中访问这些查询数据。所以像这样:

data() {
  retrun {
    START_PAGE_END_POINT: this.$page.allStartPage.edges[0].node.fields
  }
}
Run Code Online (Sandbox Code Playgroud)

给我一条错误消息并告诉我$page未定义。

知道我做错了什么吗?

Sub*_*dli 2

所以我已经弄清楚了。我能够访问vue 生命周期钩子this.$page中的变量created(),而不是data对象本身。

代码看起来像这样。null我首先在对象中定义初始值为 的变量data

data() {
      return {
        START_PAGE_END_POINT: null,

        title: null,
        subtitle: null,
        startButton: null
      }
    }
Run Code Online (Sandbox Code Playgroud)

然后在created()生命周期挂钩中,我为这些变量分配正确的值:

created() {
      if (this.$page) {
        this.START_PAGE_END_POINT = this.$page.allStartPage.edges[0].node.fields;

        this.title = this.START_PAGE_END_POINT.title,
        this.subtitle = this.START_PAGE_END_POINT.subtitle,
        this.startButton = this.START_PAGE_END_POINT.startButton
      }
    }
Run Code Online (Sandbox Code Playgroud)

我仍然好奇为什么无法访问对象本身$page的变量data