Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs: where should I place some common js util in a vue-router SPA?

In my Vuejs project, I have some common js functions which would be used through multiple components:

My code structure is as below, which was introduced in http://vuejs.github.io/vuex/en/structure.html:

├── index.html
├── main.js
├── components
│   ├── App.vue
│   └── ...
└── vuex
    ├── store.js     # exports the store (with initial state and mutations)
    └── actions.js   # exports all actions

some_component.vue

<template>
// The page content
</template>

<script>
export default {
    attached: function() {
        if(!isLoggedIn) {
            $this.router.go('/signin');
        }
    }
}
</script>

In this case, I want to make a function loginRequired which would be called in several components.

So how should I organize the code?

like image 757
Alfred Huang Avatar asked Apr 18 '16 23:04

Alfred Huang


1 Answers

Here is my choice

├── index.html
└── src
    ├── main.js
    ├── config.js        # Here I define global constants like a base url for vue-resource
    ├── api              # here is all the http calls using Vue.resource
    │   ├── index.js
    │   └── resource.js  # here I define interceptors, for errors log, auth, etc
    ├── components
    │   ├── utils        # Here I define common functions for components
    │   ├── App.vue
    │   └── ...
    └── vuex
        ├── store.js     # exports the store (with initial state and mutations)
        └── actions.js   # exports all actions

So what you want, according to my file structure, should be in the src/components/utils folder, at least that it uses some http calls, in that case, it would be part of the src/api api folder. In this case, the routes are in the main.js file, some people prefer to have a dedicated file routes.js in the src folder, it's up to you

like image 131
Yerko Palma Avatar answered Sep 19 '22 09:09

Yerko Palma