Vue 3 composition API and access to Vue instance

前端 未结 2 1863
夕颜
夕颜 2021-01-17 13:27

In main.js I have something like this:

import { myUtilFunc} from \'./helpers\';
Object.defineProperty(Vue.prototype, \'$myUtilFunc\', { value: m         


        
2条回答
  •  走了就别回头了
    2021-01-17 13:55

    Use provide/inject

    Provide

    const app = createApp(App);
    app.provide('someVarName', someVar);  // `Provide` a variable to all components here
    

    Inject:

    // In *any* component
    const { inject } = Vue;
    ...
    setup() {
      const someVar = inject('someVarName');   // injecting variable in setup
    }
    

    Note that you don't have to provide from the app root, but can also provide from any component to only its sub-components:

    // In *any* component
    setup() {
      ...
    },
    provide() {
      return {
        someVarName: someVar
      }
    }
    

    Original answer

    [Edit: While my original answer below is still useful for context properties, it's no longer recommended to use context.root, which is no longer mentioned in the guide and may soon be deprecated.]

    In Vue 3, setup has an optional second argument for context. You can access the Vue instance through context.root instead of this:

    setup(props, context) {
      context.root.$myUtilFunc  // same as `this.$myUtilFunc` in Vue 2
    }
    

    Things you can access through context:

    context.attrs
    context.slots
    context.parent
    context.root
    context.emit
    

提交回复
热议问题