gridsome(二)——數據處理

Working With Data (數據處理)

一、The GraphQL data layer(GraphQL數據層)

GraphQL數據層是在開發模式下可用的工具。這是所有導入到Gridsome項目中的數據的臨時存儲位置。可以將其視爲可幫助你更快更好地處理數據的本地數據庫。

二、Importing data

可以將數據從任何數據源導入GraphQL數據層

  • Import with source plugins

    向Gridsome添加數據的最簡單方法是使用源插件。 Gridsome數據源插件添加在gridsome.config.js中。

    module.exports = {
      plugins: [
        {
          use: '@gridsome/source-filesystem',
          options: {
            path: 'docs/**/*.md',
            typeName: 'AllPage'     //typeName將是GraphQL集合的名稱,並且必須是唯一的
          }
        }
      ]
    }
    
  • Importing from APIs

    使用數據存儲API將數據從任何內容API導入到GraphQL數據層。要使用該API,需要在Gridsome項目的根文件夾中有一個gridsome.server.js文件。

三、Querying data

可以將數據從GraphQL數據層查詢到任何頁面(Pages),模板(Templates )或組件(Components)中。在Vue組件中,使用<page-query><static-query>塊添加查詢:

  • Pages 和Templates<page-query>
  • Components<static-query>

How to query with GraphQL ❓

在Gridsome中使用GraphQL很容易,如何在頁面的<page-query>中使用GraphQL的示例:👇👇👇(可以先在playground中查詢是否有數據,之後直接複製粘貼)

  • 代碼

    • 有別名寫法

      <template>
           <div v-for="edge in $page.alias.edges" :key="edge.node.id">
            <h2>{{ edge.node.title }}</h2>
            <p>{{edge.node.comments}}</p>
          </div>
      </template>
      <page-query>
      query {
        alias:allGridsome{   //alias是別名
          edges{
            node{
              id,
              title,
              comments
            }
          }
        }
      }
      </page-query>
      
    • 無別名寫法

      <template>
      
      	<!-- 用<page-query>查詢數據的,所以下面用$page,若用<static-query>請求數據,則用$static-->
      	
           <div v-for="edge in $page.allGridsome.edges" :key="edge.node.id">    
            <h2>{{ edge.node.title }}</h2>
            <p>{{edge.node.comments}}</p>
          </div>
      </template>
      <page-query>
      	query {
      	  allGridsome{     
      	    edges{
      	      node{
      	        id,
      	        title,
      	        comments
      	      }
      	    }
      	  }
      	}
      </page-query>
      
  • 效果圖

  • 數據

    • gridsome.server.js

      module.exports = function (api) {
        api.loadSource(actions => {
          const collection = actions.addCollection('gridsome')
        
          collection.addNode({
            title: 'Gridsome',
            comments: 'how to study gridsome'
          })
        })
      }
      
      
    • playground測試

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章