Alf*_*ang 6 javascript single-page-application ecmascript-6 vue.js vue-router
在我的Vuejs项目中,我有一些通用的js函数,可通过多个组件使用:
我的代码结构如下,在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
Run Code Online (Sandbox Code Playgroud)
some_component.vue
<template>
// The page content
</template>
<script>
export default {
attached: function() {
if(!isLoggedIn) {
$this.router.go('/signin');
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我要创建一个loginRequired可以在多个组件中调用的函数。
那么我应该如何组织代码?
这是我的选择
??? 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
Run Code Online (Sandbox Code Playgroud)
因此,根据我的文件结构,您想要的内容应该在该src/components/utils文件夹中,至少要使用一些http调用,在这种情况下,它应该是src/apiapi文件夹的一部分。在这种情况下,路由位于main.js文件中,有些人希望routes.js在src文件夹中有一个专用文件,这取决于您