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

标签 javascript ecmascript-6 single-page-application 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

some_component.vue

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

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

在这种情况下,我想创建一个函数 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

所以根据我的文件结构,你想要的应该在 src/components/utils 文件夹中,至少它使用了一些 http 调用,在那种情况下,它将是src/api api 文件夹。在这种情况下,路由在 main.js 文件中,有些人更喜欢在 src 文件夹中有一个专用文件 routes.js ,由你决定

关于javascript - Vuejs : where should I place some common js util in a vue-router SPA?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706124/

相关文章:

node.js - 使用 Node.js/Express 提供 HTML 来构建简单的 SPA

javascript - Highcharts 极坐标步数

javascript - 检查数组中是否存在值

javascript - JavaScript 中的结构类型检查

javascript - ES6 - 在父构造函数方法中获取子类属性

javascript - .modal() 函数在 Angular 8 中不起作用

javascript - 我们如何更改 Highcharts 中的图例位置?

javascript - 所选城市地点自动填充的偏差结果

javascript - React 组件应该写成纯函数

javascript - 无法在 react 中同时使用按钮和链接