Muhammad Lahin
Muhammad Lahin

Reputation: 175

How to get the this instance in vue 3?

In vue 2+ I can easily get the instance of this as a result I can write something like this,

// main.js
app.use(ElMessage)

// home.vue
this.$message({
  showClose: true,
  message: 'Success Message',
  type: 'success',
})

What should I do for vue 3 as,

Inside setup(), this won't be a reference to the current active instance Since setup() is called before other component options are resolved, this inside setup() will behave quite differently from this in other options. This might cause confusions when using setup() along other Options API. - vue 3 doc.

Upvotes: 3

Views: 14959

Answers (2)

Adam R. Turner
Adam R. Turner

Reputation: 139

Providing a different method where the idea is to set a globally scoped variable to the _component property of the viewmodel/app or component:

pageVM = Vue.createApp({
                data: function () {
                    return {
                        renderComponent: true,
                        envInfo: [],
                        dependencies: [],
                        userGroups: []
                    }
                },
                mounted: function () {
                    //Vue version 3 made it harder to access the viewmodel's properties.    
                    pageVM_props = pageVM._component;
                    this.init();
                },

Upvotes: 0

tony19
tony19

Reputation: 138196

Using ElMessage directly

ElementPlus supports using ElMessage the same way as $message(), as seen in this example:

import { ElMessage } from 'element-plus'

export default {
  setup() {
    const open1 = () => {
      ElMessage('this is a message.')
    }
    const open2 = () => {
      ElMessage({
        message: 'Congrats, this is a success message.',
        type: 'success',
      })
    }

    return {
      open1,
      open2,
    }
  }
}

Using $message()

Vue 3 provides getCurrentInstance() (an internal API) inside the setup() hook. That instance allows access to global properties (installed from plugins) via appContext.config.globalProperties:

import { getCurrentInstance } from "vue";

export default {
  setup() {
    const globals = getCurrentInstance().appContext.config.globalProperties;
    return {
      sayHi() {
        globals.$message({ message: "hello world" });
      },
    };
  },
};

demo

Note: Being an internal API, getCurrentInstance() could potentially be removed/renamed in a future release. Use with caution.

Upvotes: 6

Related Questions