简体   繁体   中英

What's the correct way to initialize a Vue app?

I'm learning Vue and have seen a lot of different sample apps, documentation and how-to's. There seem to be a number of different ways that people are initializing their components and then mounting them to their app.

My question is why are there so many ways? What's the best practice around this?

For reference I'm doing my build through npm , not through an included library in an HTML file.

Option 1

const app = new Vue({
  el: '#app',
  data: function(){
  }
});

Option 2

export default {
  name: "Test",
  data() {
    
  }
};

Option 3

const app = Vue.createApp({})

// Define a new global component called button-counter
app.component('button-counter', {
  data() {
    return {
      count: 0
    }
  }
})
app.mount('#components-demo')

Option 3 for instance comes from the Vue documentation, but when I initialize an app in that way I get an error that Vue doesn't exist.

Hoping to get some clarity for myself and any other beginner that stumbles across this question.

  • Option 1 is the Vue 2 way to create an instance.

  • Option 3 is the Vue 3 way.

  • Option 2 does not initialize a new Vue instance

The correct way to instantiate is the createApp({}) function since Vue 3. The new Vue app supported only with Vue 2.

`export default {
   name: "Test",
   data() {}
};`

The above is one way to create a component named Test. Since Vue3 alternatively you can create a component with defineComponent({}) function as well

More info -> https://v3.vuejs.org/guide/instance.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM