Skip to content

Commit 1f5893f

Browse files
Added 'Add a search' to the guides and fixed a typo in Connect.vue (#312)
Co-authored-by: Travis Reynolds <travis@travisreynolds.dev>
1 parent aa5bbe0 commit 1f5893f

File tree

1 file changed

+74
-1
lines changed

1 file changed

+74
-1
lines changed

docs/guide-search.md

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,77 @@
1-
# Add search to Gridsome
1+
# Add a search to Gridsome
2+
3+
## Using local GraphQL data
4+
5+
Adding dynamic search functionality to your static site is a breeze. We can use Vue's reactive system in such scenarios.
6+
7+
Take the following query as an example:
8+
9+
```graphql
10+
{
11+
allPost {
12+
edges {
13+
node {
14+
title
15+
excerpt
16+
date
17+
path
18+
}
19+
}
20+
}
21+
}
22+
```
23+
24+
We would like to retrieve only posts that match what the user enters in the input field. So let's start by creating a `search` variable that will hold this value:
25+
26+
```js
27+
data() {
28+
return {
29+
search: ''
30+
}
31+
}
32+
```
33+
34+
We can benefit from a computed property to filter the query results before passing the data further:
35+
36+
```js
37+
computed: {
38+
searchResults() {
39+
return this.$static.allPost.edges.filter(post => {
40+
return post.node.title.toLowerCase().includes(this.search.toLowerCase().trim())
41+
})
42+
}
43+
}
44+
```
45+
46+
Notice in the code above that all the posts will be shown if the input field is blank.
47+
48+
That's it! Now we can use a `v-model` in our html template to bind the search along with the code that shows the results:
49+
50+
```html
51+
<input type="text" name="search" id="search" placeholder="Type something..." v-model="search">
52+
53+
<article v-for="post in searchResults" :key="post.node.id">
54+
<h1><g-link :to="post.node.path">{{ post.node.title }}</g-link></h1>
55+
<p>{{ post.node.excerpt }}</p>
56+
<p>{{ post.node.date }}</p>
57+
</article>
58+
```
59+
60+
You can enhance the user experience by adding a simple *empty state* text in case nothing matches:
61+
62+
```html
63+
<div v-if="searchResults.length > 0">
64+
<article v-for="post in searchResults" :key="post.node.id">
65+
<h1><g-link :to="post.node.path">{{ post.node.title }}</g-link></h1>
66+
<p>{{ post.node.excerpt }}</p>
67+
<p>{{ post.node.date }}</p>
68+
</article>
69+
</div>
70+
71+
<div v-else>
72+
<p>Your search didn't return any results. Please try again.</p>
73+
</div>
74+
```
275

376
## Using Algolia
477

0 commit comments

Comments
 (0)