vue-context-composition
makes sharing your composed state a breeze! It's the missing useContext
hook from React, reimplemented for Vue.js 3.0.
npm install --save vue-context-composition
Or with Yarn:
yarn add vue-context-composition
Define a context that can be provided and used in the component hierarchy. Pass in a create function
that will be run as part of setup()
. All Vue reactive methods such as computed
may be used.
export const userNameCtx = defineContext(() => {
const userName = ref("");
const uppercaseUserName = computed(() => userName.value.toUpperCase());
const setUserName = (name) => {
userName.value = name;
};
return {
userName: readonly(userName),
uppercaseUserName,
setUserName,
};
});
Provide context from a component in the hierarchy. All descendant components can then use that context.
import { userName } from "@contexts/user";
export default defineComponent({
setup() {
provideContext(userName);
},
});
Shorthand function to create a context that can be provided to all components in the application setup.
import { userName } from "@contexts/user";
createApp(App)
.provide(...createContext(userName))
.mount("#app");
Use context provided in an ancestor component or in application setup.
import { userName } from "@contexts/user";
export default defineComponent({
setup() {
const { uppercaseUserName, setUserName } = useContext(userName);
return {
uppercaseUserName,
setUserName,
};
},
});
See the example Vue3 project folder for a project with several examples.