This repository was archived by the owner on Dec 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathcontext.ts
70 lines (61 loc) · 2.19 KB
/
context.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { computed } from 'vue'
import type { Ref } from 'vue'
import type { Context } from '@nuxt/types'
import type { Route } from 'vue-router'
import { globalNuxt } from '@nuxtjs/composition-api/dist/runtime/globals'
import { getCurrentInstance } from './utils'
interface ContextCallback {
(context: Context): void
}
/**
* @deprecated
* Recommend using `useContext` instead
*/
export const withContext = (callback: ContextCallback) => {
const vm = getCurrentInstance()
if (!vm) throw new Error('This must be called within a setup function.')
callback((vm[globalNuxt] || vm.$options).context)
}
interface UseContextReturn
extends Omit<Context, 'route' | 'query' | 'from' | 'params'> {
route: Ref<Route>
query: Ref<Route['query']>
from: Ref<Context['from']>
params: Ref<Route['params']>
}
/**
* `useContext` will return the Nuxt context.
* @example
```ts
import { defineComponent, ref, useContext } from '@nuxtjs/composition-api'
export default defineComponent({
setup() {
const { store } = useContext()
store.dispatch('myAction')
},
})
```
*/
export const useContext = (): UseContextReturn => {
const vm = getCurrentInstance()
if (!vm) throw new Error('This must be called within a setup function.')
return {
...(vm[globalNuxt] || vm.$options).context,
/**
* @deprecated To smooth your upgrade to Nuxt 3, it is recommended not to access `route` from `useContext` but rather to use the `useRoute` helper function.
*/
route: computed(() => vm.$route),
/**
* @deprecated To smooth your upgrade to Nuxt 3, it is recommended not to access `query` from `useContext` but rather to use the `useRoute` helper function.
*/
query: computed(() => vm.$route.query),
/**
* @deprecated To smooth your upgrade to Nuxt 3, it is recommended not to access `from` from `useContext` but rather to use the `useRoute` helper function.
*/
from: computed(() => (vm[globalNuxt] || vm.$options).context.from),
/**
* @deprecated To smooth your upgrade to Nuxt 3, it is recommended not to access `params` from `useContext` but rather to use the `useRoute` helper function.
*/
params: computed(() => vm.$route.params),
}
}