vue-context-composition
TypeScript icon, indicating that this package has built-in type declarations

0.2.3 • Public • Published

Vue context composition

npm version npm downloads minified size license issues pull requests

vue-context-composition makes sharing your composed state a breeze! It's the missing useContext hook from React, reimplemented for Vue.js 3.0.

Installation

npm install --save vue-context-composition

Or with Yarn:

yarn add vue-context-composition

Usage

defineContext

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,
  };
});

provideContext

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);
  },
});

createContext

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");

useContext

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,
    };
  },
});

Example project

See the example Vue3 project folder for a project with several examples.

Package Sidebar

Install

npm i vue-context-composition

Weekly Downloads

29

Version

0.2.3

License

MIT

Unpacked Size

25.7 kB

Total Files

11

Last publish

Collaborators

  • albertbrand