【问题标题】:Access the queried data from Vue component using Gridsome使用 Gridsome 从 Vue 组件访问查询的数据
【发布时间】:2019-07-15 16:15:01
【问题描述】:

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

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

{
    "startPage": {
        "title": "Welcher Typ bist Du?",
        "subtitle": "Los geht's beim lustigen Datev-Quiz!",
        "startButton": "Quiz starten"
    }
}

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
      }
    })
  })
}

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

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

<h4 v-html="$page.allStartPage.edges[0].node.fields"></h4>

然后它工作得很好。

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

data() {
  retrun {
    START_PAGE_END_POINT: this.$page.allStartPage.edges[0].node.fields
  }
}

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

知道我做错了什么吗?

【问题讨论】:

    标签: vue.js graphql static-pages gridsome


    【解决方案1】:

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

    代码如下所示。 我首先在data对象中定义了初始值为null的变量:

    data() {
          return {
            START_PAGE_END_POINT: null,
    
            title: null,
            subtitle: null,
            startButton: null
          }
        }
    

    然后在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
          }
        }
    

    我还是很好奇为什么不能访问$page 对象本身中的$page 变量。

    【讨论】:

    • 如果你在你的组件中console.log(this),你会看到数据对象被转换成this._data并且$page在同一级别this.$page$ 表示它是某种模块,例如this.$routerthis.$store
    • 我发现您也可以在mounted() 挂钩中访问this.$pagethis.$static,如果您想将查询中的数据直接保存到data() 变量中,这会很有帮助。跨度>
    猜你喜欢
    • 2018-08-03
    • 2017-10-17
    • 2020-07-23
    • 2018-08-09
    • 2018-11-03
    • 2019-11-05
    • 2022-01-22
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多