Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the queried data from Vue component using Gridsome

I am new to Gridsome as well as to GraphQL. However I'm not using the GraphQL for this project. I just have a Gridsome project setup and some JSON data and I'm trying to define it globally so that I can access it from all my Vue pages and Components. (I know it can be imported into the component but I'm looking for more "Gridsome way" of doing that). I've done following steps to achieve this:

1) Created a folder for the Json file: data/myJson.json. Json-file:

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

2) My gridsome.server.js is looking like this:

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) And I'm querying this data in the index.vue page.

I can acces this data in my template. So if I do something like this

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

then it works perfectly fine.

My problem is however, that I can't acces this queried data within Vue's data object or within methods and so on. So something like this:

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

gives me an error message and tells that the $page is not defined.

Any minds what I'm doing wrong?

like image 685
Subhan Asadli Avatar asked Feb 21 '19 16:02

Subhan Asadli


1 Answers

So I've figured it out. I was able to access this.$page variable in the created() lifecycle hook of vue and not in the data object itself.

The code is looking like this. I first define the variables with initial value of null in the data object:

data() {
      return {
        START_PAGE_END_POINT: null,

        title: null,
        subtitle: null,
        startButton: null
      }
    }

Then in the created() lifecycle hook I'm assigning the right values to theese variables:

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

I'm still curious why is it not possible to access the $page variable in the data object itself.

like image 53
Subhan Asadli Avatar answered Nov 03 '22 04:11

Subhan Asadli