Skip to content
This repository has been archived by the owner on Dec 5, 2024. It is now read-only.

Commit

Permalink
feat: add withContext hook
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Apr 27, 2020
1 parent 653c308 commit 179f0e1
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@
## Progress

- [x] Support for new Nuxt `fetch()`
- [ ] Access to Nuxt context
- [x] Access to Nuxt context
- [ ] `nuxtServerInit`
- [ ] Vuex hooks

## Quick Start

Expand Down Expand Up @@ -69,6 +68,23 @@ export default defineComponent({
})
```

### withContext

You can access the Nuxt context more easily using `withContext`, which runs synchronously within the setup function.

```ts
import { defineComponent, ref } from '@vue/composition-api'
import { withContext } from 'nuxt-composition-api'

export default defineComponent({
setup() {
withContext(({ store }) => {
store.dispatch('myAction
})
},
})
```
## Contributors
Contributions are very welcome.
Expand Down
13 changes: 13 additions & 0 deletions src/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { getCurrentInstance } from '@vue/composition-api'
import { Context } from '@nuxt/types'

interface ContextCallback {
(context: Context): void
}

export const withContext = (callback: ContextCallback) => {
const vm = getCurrentInstance()
if (!vm) throw new Error('This must be called within a setup function.')

callback(vm.$nuxt.context)
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ import CompositionApi from '@vue/composition-api'
Vue.use(CompositionApi)

export { onFetch } from './fetch'
export { withContext } from './context'

0 comments on commit 179f0e1

Please sign in to comment.