### Install Nuxt Composition API Module Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/1.getting-started/2.setup.md This snippet provides commands to install the `@nuxtjs/composition-api` module using either Yarn or npm. This module is essential for integrating Vue Composition API features into a Nuxt.js project. ```bash yarn add @nuxtjs/composition-api ``` ```bash npm install @nuxtjs/composition-api --save ``` -------------------------------- ### Fetching Data with useAsync and Nuxt HTTP Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/6.API/1.useAsync.md This TypeScript example demonstrates using `useAsync` within a Nuxt.js component's `setup` function to fetch data. It utilizes the `$http` instance from the `@nuxt/http` module to make an API call to `/api/posts`. The `posts` variable becomes a reactive reference holding the fetched data. This setup requires `@nuxt/http` to be installed and configured in your `nuxt.config.js`. ```TypeScript import { defineComponent, useAsync, useContext } from '@nuxtjs/composition-api' export default defineComponent({ setup() { const { $http } = useContext() const posts = useAsync(() => $http.$get('/api/posts')) return { posts } } }) ``` -------------------------------- ### Install Dependencies and Build Nuxt Composition API Project Source: https://github.com/nuxt-community/composition-api/blob/main/README.md These commands install the project dependencies, compile the library, watch for changes, start a test Nuxt fixture, and run tests. This is essential for local development and testing of the `@nuxtjs/composition-api` module. ```bash yarn # Compile library and watch for changes yarn watch # Start a test Nuxt fixture with hot reloading yarn fixture # Test yarn test ``` -------------------------------- ### Run function in global Nuxt setup with onGlobalSetup Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/4.lifecycle/1.onGlobalSetup.md This snippet demonstrates how to use `onGlobalSetup` from `@nuxtjs/composition-api` within a Nuxt plugin. It allows providing global data or running setup functions that are accessible throughout the application. It's crucial to call this from a plugin, not a component. ```typescript import { onGlobalSetup, provide } from '@nuxtjs/composition-api' export default () => { onGlobalSetup(() => { provide('globalKey', true) }) } ``` -------------------------------- ### Enable Nuxt Composition API Module in nuxt.config.js Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/1.getting-started/2.setup.md This snippet shows how to enable the `@nuxtjs/composition-api` module by adding it to the `buildModules` array in your `nuxt.config.js` file. For Nuxt versions older than 2.9, it should be added to `modules` instead. ```js { buildModules: [ '@nuxtjs/composition-api/module' ] } ``` -------------------------------- ### Basic Vuex Store Access with useStore in Nuxt Composition API Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/2.packages/2.store.md Illustrates the fundamental way to retrieve the Vuex store instance within a Nuxt 2 component's `setup` function using the `useStore` helper from `@nuxtjs/composition-api`. ```typescript import { defineComponent, useStore } from '@nuxtjs/composition-api' export default defineComponent({ setup() { const store = useStore() }, }) ``` -------------------------------- ### Clone Nuxt Composition API Repository Source: https://github.com/nuxt-community/composition-api/blob/main/README.md This command clones the Nuxt Composition API repository from GitHub, allowing you to get a local copy of the project for development or contribution. ```bash git clone git@github.com:nuxt-community/composition-api.git ``` -------------------------------- ### Implementing useFetch for Data Fetching in Nuxt Composition API Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/4.lifecycle/2.useFetch.md This TypeScript snippet demonstrates how to integrate `useFetch` within a Nuxt 2.12+ component's `setup()` function for asynchronous data fetching. It shows how to use `axios` to fetch data, assign it to a `ref`, manually trigger a refetch, and access the `fetchState` for error, pending, and timestamp information. Important considerations include calling `useFetch` synchronously within `setup()`, using `ref`s instead of `ssrRef`s to prevent double state serialization, and noting that `$fetch` and `$fetchState` are automatically available on the component instance. ```ts import { defineComponent, ref, useFetch } from '@nuxtjs/composition-api' import axios from 'axios' export default defineComponent({ setup() { const name = ref('') const { fetch, fetchState } = useFetch(async () => { name.value = await axios.get('https://myapi.com/name') }) // Manually trigger a refetch fetch() // Access fetch error, pending and timestamp fetchState return { name } } }) ``` -------------------------------- ### Install Nuxt Composition API Module Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/index.md Command to add the @nuxtjs/composition-api module to your Nuxt 2 project using Yarn. This module integrates the Vue Composition API features into your Nuxt application. ```Shell yarn add @nuxtjs/composition-api ``` -------------------------------- ### Wrap Vue Instance Property with Composition API Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/6.API/4.wrap.md Demonstrates how to use `wrapProperty` from `@nuxtjs/composition-api` to create a custom helper for a Vue instance property. The example shows converting a `$accessor` property into a Composition-ready one, allowing access to a fully typed store accessor within a component's `setup` function. The second argument to `wrapProperty` controls whether a computed property is returned. ```TypeScript import { defineComponent, wrapProperty } from '@nuxtjs/composition-api' // For example, for used with https://github.com/danielroe/typed-vuex const useAccessor = wrapProperty('$accessor', false) export default defineComponent({ setup() { const accessor = useAccessor() // You can now access a fully typed store accessor in your component }, }) ``` -------------------------------- ### Access Router Instance with Nuxt Composition API's useRouter Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/2.packages/1.routes.md Illustrates how to use `useRouter` to get the `this.$router` instance in a Nuxt 2 component with the Composition API. This allows for programmatic navigation, such as pushing a new route. ```ts import { defineComponent, useRouter } from '@nuxtjs/composition-api' export default defineComponent({ setup() { const router = useRouter() router.push('/') }, }) ``` -------------------------------- ### Define Head and Meta Properties with useMeta in Nuxt Composition API Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/2.packages/3.useMeta.md This TypeScript snippet demonstrates how to use `useMeta` within a Nuxt 3 component's `setup` function to manage document head properties like title and meta tags. It shows various ways to assign values, including direct assignment, initial values, and reactive updates using computed properties. It highlights the necessity of defining an empty `head: {}` object in the component options and using `defineComponent` from `@nuxtjs/composition-api`. ```ts import { defineComponent, useMeta, computed, ref } from '@nuxtjs/composition-api' export default defineComponent({ // You need to define an empty head to activate this functionality head: {}, setup() { // This will allow you to set the title in head - but won't allow you to read its state outside of this component. const { title } = useMeta() title.value = 'My page' // You could also provide an initial value. const { title } = useMeta({ title: 'My page' }) // ... or simply set some meta tags useMeta({ title: 'My page', ... }) // You can even pass a function to achieve a computed meta const message = ref('') useMeta(() => ({ title: message.value })) } }) ``` -------------------------------- ### Incorrect Usage of Keyed Functions in Composables Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/1.getting-started/3.gotchas.md This example demonstrates the pitfall of using keyed helper functions like `ssrRef` within a global composable without providing a unique key. By default, the library generates a key based on the line number, leading to the same key being used for multiple calls to the composable. Consequently, on the client-side, all instances initialized with the same key will share the same value, as shown when `b.value` affects `a.value`. ```ts function useMyFeature() { // Only one unique key is generated, no matter // how many times this function is called. const feature = ssrRef('') return feature } const a = useMyFeature() const b = useMyFeature() b.value = 'changed' // On client-side, a's value will also be initialised to 'changed' ``` -------------------------------- ### Access Nuxt Context with useContext in TypeScript Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/6.API/2.useContext.md This snippet demonstrates how to access the Nuxt context using `useContext` within a Vue component's `setup` function. Note that `route`, `query`, `from`, and `params` are reactive refs (accessed with `.value`), while the rest of the context is not. For smoother upgrades to Nuxt 3, it is recommended to use the `useRoute` helper function instead of accessing `route`, `query`, `from`, and `params` from `useContext`. ```ts import { defineComponent, useContext } from '@nuxtjs/composition-api' export default defineComponent({ setup() { const { store } = useContext() store.dispatch('myAction') }, }) ``` -------------------------------- ### Using ssrPromise for Server-Side Promise Resolution in Vue Composition API Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/5.data/2.ssrPromise.md This snippet demonstrates how to use `ssrPromise` within a Vue 3 Composition API `setup()` function to execute an asynchronous operation on the server. The result is then serialized and made available as a resolved promise on the client. The `onBeforeMount` lifecycle hook is used to await and assign the resolved value to a reactive reference, ensuring the data is ready before the component mounts on the client. ```typescript import { defineComponent, onBeforeMount, ref, ssrPromise } from '@nuxtjs/composition-api' export default defineComponent({ setup() { const _promise = ssrPromise(async () => myAsyncFunction()) const resolvedPromise = ref(null) onBeforeMount(async () => { resolvedPromise.value = await _promise }) return { // On the server, this will be null until the promise resolves. // On the client, if server-rendered, this will always be the resolved promise. resolvedPromise } } }) ``` -------------------------------- ### Define async data fetching with useStatic in Nuxt.js Composition API Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/6.API/3.useStatic.md This TypeScript code demonstrates how to use `useStatic` within a Nuxt.js component to fetch data asynchronously. It utilizes `axios` to get a post by ID, ensuring the data is pre-rendered or cached for performance. The `useStatic` function takes a factory function, a key, and a unique identifier. ```ts import { defineComponent, useContext, useStatic, computed, } from '@nuxtjs/composition-api' import axios from 'axios' export default defineComponent({ setup() { const { params } = useContext() const id = computed(() => params.value.id) const post = useStatic( id => axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`), id, 'post' ) return { post } }, }) ``` -------------------------------- ### Example reqRef usage for server-side state in Nuxt Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/5.data/1.reqRef.md This TypeScript snippet demonstrates how to use `reqRef` from `@nuxtjs/composition-api` to declare a server-side ref (`user`) that automatically resets its value on each new request. It also shows an asynchronous function (`fetchUser`) that populates this ref with data fetched from an API. This pattern is useful for managing per-request state on the server, but developers must be mindful of potential shared state issues. ```ts import { reqRef } from '@nuxtjs/composition-api' export const user = reqRef(null) export const fetchUser = async () => { const r = await fetch('https://api.com/users') user.value = await r.json() } ``` -------------------------------- ### Define and Hydrate Server-Side State with ssrRef in TypeScript Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/5.data/3.ssrRef.md `ssrRef` allows defining reactive data on the server that gets stringified and hydrated on the client. It automatically adds ref values to `window.__NUXT__` on SSR if they change from their initial value. It supports factory functions for initial value generation and can be used outside components. A Babel plugin typically handles automatic keying for client-server matching. ```ts import { ssrRef } from '@nuxtjs/composition-api' const val = ssrRef('') // When hard-reloaded, `val` will be initialised to 'server set' if (process.server) val.value = 'server set' // When hard-reloaded, the result of myExpensiveSetterFunction() will // be encoded in nuxtState and used as the initial value of this ref. // If client-loaded, the setter function will run to come up with initial value. const val2 = ssrRef(myExpensiveSetterFunction) ``` -------------------------------- ### Correct Usage of Keyed Functions with Unique Keys Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/1.getting-started/3.gotchas.md This snippet illustrates the correct way to use keyed helper functions, such as `useAsync`, within a composable by providing a unique key as the second argument. In this case, the `path` parameter is used as the key, ensuring that each invocation of `useMyFeature` with a different path generates a distinct server-to-client data transfer, preventing unintended state sharing. ```ts function useMyFeature(path: string) { const content = useAsync( () => fetch(`https://api.com/slug/${path}`).then(r => r.json()), path ) return { content, } } export default useMyFeature ``` -------------------------------- ### Define Nuxt Plugin with Typescript Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/3.typings/1.definitionHelpers.md This snippet demonstrates how to create a Nuxt plugin with automatic type-hinting using the `defineNuxtPlugin` helper. It imports the helper from `@nuxtjs/composition-api` and exports a default plugin function, ensuring the `ctx` parameter has correct typings for enhanced developer experience. ```typescript import { defineNuxtPlugin } from '@nuxtjs/composition-api' export default defineNuxtPlugin(ctx => { // do stuff }) ``` -------------------------------- ### Define Nuxt Middleware with Typescript Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/3.typings/1.definitionHelpers.md This snippet illustrates how to create Nuxt middleware with automatic type-hinting using the `defineNuxtMiddleware` helper. It imports the helper from `@nuxtjs/composition-api` and exports a default middleware function, providing correct typings for the `ctx` parameter to improve code reliability and development speed. ```typescript import { defineNuxtMiddleware } from '@nuxtjs/composition-api' export default defineNuxtMiddleware(ctx => { // do stuff }) ``` -------------------------------- ### Typing Vuex Store with InjectionKey or Generic Type in Nuxt Composition API Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/2.packages/2.store.md Demonstrates how to enhance type safety when accessing the Vuex store via `useStore` by either providing an `InjectionKey` or specifying a generic type parameter, ensuring correct type inference for store properties. ```typescript import { defineComponent, useStore } from '@nuxtjs/composition-api' export interface State { count: number } export const key: InjectionKey> = Symbol() export default defineComponent({ setup() { const store = useStore(key) const store = useStore() // In both of these cases, store.state.count will be typed as a number }, }) ``` -------------------------------- ### Create Shallow Reactive Server-Client Synced Refs with shallowSsrRef in TypeScript Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/5.data/3.ssrRef.md `shallowSsrRef` creates a `shallowRef` that is synchronized between the client and server. Unlike a regular ref, a `shallowRef` only tracks its own `.value` mutation and does not make its value reactive. This helper is useful for conveying server-side state to the client where deep reactivity is not required, optimizing performance. ```ts import { shallowSsrRef, onMounted } from '@nuxtjs/composition-api' const shallow = shallowSsrRef({ v: 'init' }) if (process.server) shallow.value = { v: 'changed' } // On client-side, shallow.value will be { v: changed } onMounted(() => { // This and other changes outside of setup won't trigger component updates. shallow.value.v = 'Hello World' }) ``` -------------------------------- ### Access Current Route with Nuxt Composition API's useRoute Source: https://github.com/nuxt-community/composition-api/blob/main/docs/pages/en/2.packages/1.routes.md Demonstrates how to use `useRoute` to access `this.$route` in a Nuxt 2 component using the Composition API. The returned route object is wrapped in a computed property, requiring `.value` to access its properties like `params.id`. ```ts import { computed, defineComponent, useRoute } from '@nuxtjs/composition-api' export default defineComponent({ setup() { const route = useRoute() const id = computed(() => route.value.params.id) }, }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.