diff --git a/docs/cookbook/shared-state.md b/docs/cookbook/shared-state.md new file mode 100644 index 000000000..e22911339 --- /dev/null +++ b/docs/cookbook/shared-state.md @@ -0,0 +1,157 @@ +--- +title: Shared State +description: How to use a reactive composable to share your objects across component files. +author: whitespacecode +thumbnail: /recipes/animations.png +difficulty: 0 +--- + +# Shared State in TresJS + +This guide will help you get started with shared state in TresJS by building a simple scene with a cube that can be shared across component files. + + + +## Creating a State Composable + +First, we'll create a composable to store the objects. + +### Setting the object to the state +Next, we'll assign an object to the state and include it in a subcomponent where we can access and use it. + +### Using the object in other components +With the mesh assigned to the reactive state, it's available throughout your project. + +::: code-group + +```vue [App.vue] + + + +``` + +```vue [Subcomponent.vue] + + + +``` + +```ts [composables/state.ts] +import { reactive, toRefs } from "vue"; + +const state = reactive({ + mesh: null, + //you can add more objects here +}) + +export function useState() { + return { + ...toRefs(state) + } +} +``` +::: + +## Using TresMesh components + +You can also add TresMesh components to the reactive state. Here, we'll use a reference and assign it to the state when mounted. + +```vue + + + +``` + +## Using Pinia Store + +By using the same logic we can also use Pinia. +By using pinia we also have full access to actions and getters. + +::: code-group + +```ts [model.ts] +import { defineStore } from "pinia"; + +export const useModelStore = defineStore('model', { + state: () => { + return { + exampleModel: null, + } + }, + actions: {}, +}); +``` + +```vue [App.vue] + + + +``` + +::: + +With these steps, you can easily manage and share objects across different components in your Vue 3 project using a reactive composable.