Skip to content

Instantly share code, notes, and snippets.

@ben-rogerson
Last active October 18, 2018 19:07
Show Gist options
  • Save ben-rogerson/0b999b74c71fed19c051e3d4ab9ab599 to your computer and use it in GitHub Desktop.
Save ben-rogerson/0b999b74c71fed19c051e3d4ab9ab599 to your computer and use it in GitHub Desktop.
Vue Craft GraphQL Search Component
import Vue from 'vue/dist/vue.esm';
import axios from 'axios';
Vue.config.productionTip = false
// Information needed for connecting to our CraftQL endpoint
const apiToken = '[ADD KEY HERE]';
const apiUrl = '/api';
// What to search for
const searchSections = ['blog'];
const searchPrefix = 'title:';
// The query to search for entries in Craft
const searchQuery = `
query searchQuery($sections: [SectionsEnum], $needle: String!, $limit: Int)
{
entries(section: $sections, search: $needle, limit: $limit) {
title
url
}
}
`;
// Configure the api endpoint
const configureApi = (url, token) => {
return {
baseURL: url,
headers: {
Authorization: `Bearer ${token}`,
'X-Requested-With': 'XMLHttpRequest'
}
};
};
// Execute a GraphQL query by sending an XHR to our api endpoint
const executeQuery = (api, query, variables, callback) => {
api.post('', {
query: query,
variables: variables
}).then(result => {
if (callback) callback(result.data);
console.log(result.data);
}).catch(error => {
console.log(error);
})
};
// Instantiate our Vue instance
new Vue({
el: '#demo',
data: {
searchApi: axios.create(configureApi(apiUrl, apiToken)),
searchQuery: '',
searchResults: {}
},
methods: {
// Perform a search
performSearch() {
// If they haven't entered anything to search for, return nothing
if (this.searchQuery === '') {
this.searchResults = {};
return;
}
// Set the variables we will pass in to our query
const variables = {
sections: searchSections,
needle: searchPrefix + this.searchQuery,
limit: 5
};
// Execute the query
executeQuery(this.searchApi, searchQuery, variables, (data) => {
this.searchResults = data.data.entries;
});
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment