Client-side data is data added after page load. This can be data coming from other internal pages, a REST API or a GraphQL API. It's important to only load your data in the mounted
hook to prevent it from being included in the generated markup.
Fetch page-query
results and page context from other internal pages. The following example fetches data from /other-page
and stores the results.
export default {
data () {
return {
otherPage: null
}
},
async mounted () {
try {
const results = await this.$fetch('/other-page')
this.otherPage = results.data
} catch (error) {
console.log(error)
}
}
}
The fetch
method can also be imported from gridsome
.
import { fetch } from 'gridsome'
export default {
async mounted () {
const results = await fetch('/other-page')
console.log(results.data)
}
}
Read more about the $fetch() method.
import axios from 'axios'
export default {
data () {
return {
todos: null
}
},
async mounted () {
try {
const results = await axios.get(
'https://jsonplaceholder.typicode.com/todos'
)
this.todos = results.data
} catch (error) {
console.log(error)
}
}
}
import {GraphQLClient} from 'graphql-request';
export default {
async mounted() {
const client = new GraphQLClient('https://countries.trevorblades.com/');
const countries = await client.request('{ countries { name } }');
}
}
The following example fetches local YAML files within .vue templates:
/src/data
folder. For example: products.yaml
import products from @/data/products.yaml
before export default
function.products
and defining it with the just imported products
. Since the object key and the value are the same, we can destructure to just products
.<template>
<ul>
<li v-for="product in products" :key="product.title">{{ product.title }}</li>
</ul>
</template>
<script>
import products from '@/data/products.yaml'
export default {
data() {
return {
products
}
}
}
</script>
The following example fetches local JSON data within .vue templates:
/src/data
folder. For example: users.json
import users from @/data/users.json
before export default
function.users
and defining it with the just imported users
. Since the object key and the value are the same, we can destructure to just users
.<template>
<ul>
<li v-for="user in users" :key="user.name">{{ user.name }}</li>
</ul>
</template>
<script>
import users from '@/data/users.json'
export default {
data() {
return {
users
}
}
}
</script>