Search code examples
vue.jsvue-cli-3

Vue.js differences


Stupid question, I just start learning Vue.js and I've seen two ways of people using it and I'm a bit confuse and was wondering if someone can explain it to me. Is it that example one is used when creating individual web pages and the second is used when creating SPA application using the Vue CLI which is a more component base?

Example one:

var vm = new Vue({
el: '#example',
  data: {
  message: 'Hello'
   }
 })

Example two:

<script>
 export default {
    name: 'Chat',
    data() {
        return {

        }
    },
    methods: {

       }
     }
 </script>

Solution

  • The first creates a new 'Vue' instance. Think of it as basically telling Vue to switch on. You need this in every Vue project, whether it be an SPA or something a bit more complex.

    The latter creates a component that is ready to be imported into the Vue instance. For example, this is how a typical 'main' file would look like in a Vue.js project:

    import Vue from 'vue'    
    import NewComponent from './some-file-path/some-file-name.vue'
    
    Vue.component('NewComponent', NewComponent) // register the component
    
    new Vue({
        el: '#example'
    }) // initiate a Vue instance
    

    For the most part, you should be using both of the examples that you posted. The first, to set up the Vue project, and the other to add components.