What is the purpose of main.js & App.vue in Vue App

Sanyam Jain picture Sanyam Jain · Nov 21, 2019 · Viewed 12.4k times · Source

I don't understand the exact purpose of each file.
Suppose, I want to put authentication code, where should I place it, in main.js or App.vue

Answer

Tom 'Blue' Piddock picture Tom 'Blue' Piddock · Nov 21, 2019

I believe you might be missing on some of the basics behind the structure of VueJS and where and/or how to put in functionality like authentication. It might be worth going through their Introduction again to solidify your knowledge.

To answer more directly, when you run a Vue JS application you need to have a basic html page (like index.html) as an entry point and the intialisation for your Vue app loaded in a <script> in that page.

When you write a Vue JS application you can choose to do it in pure JavaScript, in TypeScript or in the .vue component format which combines the HTML, CSS and JavaScript you need to define components.

The vue format is not run directly, it has to be transpiled into plain JavaScript by the Vue-CLI/builder and packed using a packager like WebPack first and then loaded by your entry point. Luckily the Vue CLI handles nearly all of this process so you can get on with building.

App.vue

This is typically the root of your application defined in Vue Component file format. It's usually something that defines the template for your page:

<template>
  <div id="app">
    <SideBar /> 
    <router-view v-if="loaded" /> 
  </div>
</template>

<script>
import SideBar from "./pages/SideBar";

export default {
  components: { SideBar },
  computed: {
    loaded() {
      return this.$store.state.loadState == "loaded";
    }
  }
};
</script> 

main.js

This is usually the JavaScript file that will initialise this root component into a element on your page. It is also responsible for setting up plugins and 3rd party components you may want to use in your app:

import Vue from "vue";
import { store } from "./store/store";
import router from "./router";
import App from "./App.vue";

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

index.html

The index page provides your entry point in html providing an element for VueJs to load into and imports main.js to intialise your app.

<!-- the html element that hosts the App.vue component -->
<div id="app"></div>

<!-- built files will be auto injected -->
<script type="text/javascript" src="main.js"></script>  

On another note a decent place to put your authentication logic is in the router where you can add navigation guards to restrict access to pages based on the current authentication state and send your users to a login page:

// GOOD
router.beforeEach((to, from, next) => {
  if (!isAuthenticated) next('/login')
  else next()
})