vue 3 before create event in main.js

6.2k Views Asked by At

I'm trying to use beforeCreate in main.js. What is the equivalence of this code in Vue 3?

new Vue({
  el: '#app',
  router,
  components: { App },
  store: store,
  beforeCreate() { this.$store.commit('initialiseStore');},
  template: '<App/>'
})
1

There are 1 best solutions below

0
tony19 On BEST ANSWER

beforeCreate() still exists in Vue 3's Options API.

For that code snippet, the only differences in Vue 3 would be:

  1. The creation of the app instance is now done via Vue.createApp().

    Note: In the following example, we're using extends: App here so that we could add the beforeCreate() hook. Otherwise, we could simply do createApp(App) instead.

  2. The Vue plugins are installed off of the app instance's use() method.

  3. The mounting is done via the app instance's mount() method.

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

1️⃣
createApp({
    extends: App,
    beforeCreate() { this.$store.commit('initialiseStore') }
  })
  2️⃣
  .use(router)
  .use(store)
  3️⃣
  .mount('#app')

demo

Side note: Since you're migrating to Vue 3, Pinia is now the officially recommended state management library that replaces Vuex (now deprecated). See Pinia's migration guide.