Skip to content

Commit 787658e

Browse files
Add asyncData method
1 parent edbde76 commit 787658e

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

resources/js/layouts/error.vue

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<template>
2+
<div class="error-layout text-center mt-4">
3+
<h1>{{ $t('error_alert_title') }}</h1>
4+
<p>{{ $t('error_alert_text') }}</p>
5+
</div>
6+
</template>
7+
8+
<script>
9+
export default {
10+
name: 'ErrorLayout'
11+
}
12+
</script>

resources/js/pages/home.vue

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,18 @@
99
</template>
1010

1111
<script>
12+
// import axios from 'axios'
1213
export default {
1314
middleware: 'auth',
1415
16+
// async asyncData () {
17+
// const { data: projects } = await axios.get('/api/projects')
18+
19+
// return {
20+
// projects
21+
// }
22+
// },
23+
1524
metaInfo () {
1625
return { title: this.$t('home') }
1726
}

resources/js/router/index.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,9 @@ async function beforeEach (to, from, next) {
7474
// Get the middleware for all the matched components.
7575
const middleware = getMiddleware(components)
7676

77+
// Load async data for all the matched components.
78+
await asyncData(components)
79+
7780
// Call each middleware.
7881
callMiddleware(middleware, to, from, (...args) => {
7982
// Set the application layout only if "next()" was called with no args.
@@ -85,6 +88,37 @@ async function beforeEach (to, from, next) {
8588
})
8689
}
8790

91+
/**
92+
* @param {Array} components
93+
* @return {Promise<void>
94+
*/
95+
async function asyncData (components) {
96+
for (let i = 0; i < components.length; i++) {
97+
const component = components[i]
98+
99+
if (!component.asyncData) {
100+
continue
101+
}
102+
103+
const dataFn = component.data
104+
105+
try {
106+
const asyncData = await component.asyncData()
107+
108+
component.data = function () {
109+
return {
110+
...(dataFn ? dataFn.apply(this) : {}),
111+
...asyncData
112+
}
113+
}
114+
} catch (e) {
115+
component.layout = 'error'
116+
117+
console.error('Failed to load asyncData', e)
118+
}
119+
}
120+
}
121+
88122
/**
89123
* Global after hook.
90124
*

0 commit comments

Comments
 (0)