11

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?

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
Alfred Huang
  • 17,654
  • 32
  • 118
  • 189

1 Answers1

9

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

Alfred Huang
  • 17,654
  • 32
  • 118
  • 189
Yerko Palma
  • 12,041
  • 5
  • 33
  • 57
  • And should I define utils as a module (namespace in fact) and then `let utils = require('./components/utils.js')` to use it ? – Alfred Huang Apr 22 '16 at 00:48
  • In fact I use it like a folder, and then make as many files as I need. There are others projects that works like [this](https://github.com/yuche/vue-strap/tree/master/src/utils) – Yerko Palma Apr 22 '16 at 01:49
  • Finally, take a look at [this project](https://github.com/jackhutu/jackblog-vue/tree/master/src), from here I adapted my file structure – Yerko Palma Apr 22 '16 at 01:54
  • Excellent! Thank you! – Alfred Huang Apr 22 '16 at 03:23