Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue 3 composition API and access to Vue instance

In main.js I have something like this:

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

In this way I have acess to myUtilFunc across whole application with this.$myUtilFunc

But how can I achieve the same in setup() method in Vue 3 if I don't have access to this?

like image 845
Stanislav Avatar asked Feb 13 '20 07:02

Stanislav


People also ask

Can I use options API in Vue 3?

While Vue does support TypeScript usage with Options API, it is recommended to use Vue with TypeScript via Composition API as it offers simpler, more efficient and more robust type inference.

How do I access Vue instance inside a JS file in vue3?

export const app = createApp({ render() { return h(AppWrapper); }, }); Next, we would have to register our component in our globalProperties of our app's instance. Save this answer.

How do I access my Vue 3 router?

Using <router-view> and <router-link> There are two directives our Vue application gives us to use in our template: <router-view /> - When a route is navigated to in the browser, this is where the component is rendered. For example, in our code going to / will render the Home component where we list <router-view /> .


1 Answers

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
like image 68
Dan Avatar answered Oct 22 '22 20:10

Dan