Skip to content

Latest commit

 

History

History
113 lines (89 loc) · 2.98 KB

README.md

File metadata and controls

113 lines (89 loc) · 2.98 KB

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.