建立和维护大型 Vue.js 项目的 10 个最佳实践

2022-07-06  本文已影响0人  BingJS

1.使用插槽(slot)使组件更易于理解并且功能更强大

<template>
  <div class="c-base-popup">
    <div v-if="$slots.header" class="c-base-popup__header">
      <slot name="header">
    </div>
    <div v-if="$slots.subheader" class="c-base-popup__subheader">
      <slot name="subheader">
    </div>
    <div class="c-base-popup__body">
      <h1>{{ title }}</h1>
      <p v-if="description">{{ description }}</p>
    </div>
    <div v-if="$slots.actions" class="c-base-popup__actions">
      <slot name="actions">
    </div>
    <div v-if="$slots.footer" class="c-base-popup__footer">
      <slot name="footer">
    </div>
  </div>
</template>
<script> 
export default {
  props: {
    description: {
      type: String,
      default: null
    },
    title: {
      type: String,
      required: true
    }
  }
} 
</script> 

由知道何时使用插槽的开发人员构建的项目确实对其未来的可维护性有很大的影响。
这样就可以减少发出事件的次数,使代码更易于理解,并且可以在内部显示所需的任何组件时提供更大的灵活性。

请记住,当最终在子组件的父组件中复制子组件的属性时,应该从这一点开始使用插槽。

2.正确组织您的 Vuex 存储

大多数开发人员都喜欢按功能组织它们。

从API提取的数据模型来组织它们时更容易理解。

您选择哪一个取决于您。唯一要记住的是,从长远来看,组织良好的 Vuex 存储将使团队更具生产力。这也将使新来者更容易在加入您的团队时就将您的想法围绕您的代码库。

3.使用操作(Vuex Actions)进行 API 调用和提交数据

大多数API调用(如果不是全部)都在我的 Vuex 操作(vuex actions)中进行。为什么这里调用更好?
提取了在(vuex store)中存储的数据,们提供了真正的封装性和可重用性。

译注:Mixpanel 是一家数据跟踪和分析公司,允许开发者跟踪各种用户行为,比如用户浏览的页面数,iPhone 应用分析,Facebook 应用互动情况,以及 Email 分析。类似Firebase一样的埋点分析工具。

4.使用 mapState,mapGetters,mapMutations 和 mapAction 简化代码库

import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
  computed: {
    // Accessing root properties
    ...mapState("my_module", ["property"]),
    // Accessing getters
    ...mapGetters("my_module", ["property"]),
    // Accessing non-root properties
    ...mapState("my_module", {
      property: state => state.object.nested.property
    })
  },
  methods: {
    // Accessing actions
    ...mapActions("my_module", ["myAction"]),
    // Accessing mutations
    ...mapMutations("my_module", ["myMutation"])
  }
}; 

5.使用 API 工厂

创建一个this.$api可以在任何地方调用以获取API端点的助手。
在项目的根目录下,创建api文件夹,包含所有类。

api 
├── auth.js
├── notifications.js
└── teams.js 

在 Nuxt 应用程序中使用插件初始化此模式的方式(这与标准 Vue 应用程序中的过程非常相似)。

// PROJECT: API
import Auth from "@/api/auth";
import Teams from "@/api/teams";
import Notifications from "@/api/notifications";
export default (context, inject) => {
  if (process.client) {
    const token = localStorage.getItem("token");
    // Set token when defined
    if (token) {
      context.$axios.setToken(token, "Bearer");
    }
  }
  // Initialize API repositories
  const repositories = {
    auth: Auth(context.$axios),
    teams: Teams(context.$axios),
    notifications: Notifications(context.$axios)
  };
  inject("api", repositories);
}; 
export default $axios => ({
  forgotPassword(email) {
    return $axios.$post("/auth/password/forgot", { email });
  },
  login(email, password) {
    return $axios.$post("/auth/login", { email, password });
  },
  logout() {
    return $axios.$get("/auth/logout");
  },
  register(payload) {
    return $axios.$post("/auth/register", payload);
  }
}); 

现在,我可以简单地在我的组件或 Vuex 操作中调用它们,如下所示:

export default {
  methods: {
    onSubmit() {
      try {
        this.$api.auth.login(this.email, this.password);
      } catch (error) {
        console.error(error);
      }
    }
  }
}; 

6.使用 $config 访问您的环境变量(在模板中特别有用)

您的项目可能在某些文件中定义了一些全局配置变量:

config
├── development.json
└── production.json 
import development from "@/config/development.json";
import production from "@/config/production.json";
if (process.env.NODE_ENV === "production") {
  Vue.prototype.$config = Object.freeze(production);
} else {
  Vue.prototype.$config = Object.freeze(development);
} 

7.遵循一个约定来写提交注释

随着项目的发展,您将需要定期浏览组件的提交历史记录。如果您的团队没有遵循相同的约定来书写他们的提交说明,那么将很难理解每个团队成员的行为。

8.始终在生产项目时冻结软件包的版本

避免使用以^开头的版本:

{
  "name": "my project",
  "version": "1.0.0",
  "private": true,
  "dependencies": {
    "axios": "0.19.0",
    "imagemin-mozjpeg": "8.0.0",
    "imagemin-pngquant": "8.0.0",
    "imagemin-svgo": "7.0.0",
    "nuxt": "2.8.1",
  },
  "devDependencies": {
    "autoprefixer": "9.6.1",
    "babel-eslint": "10.0.2",
    "eslint": "6.1.0",
    "eslint-friendly-formatter": "4.0.1",
    "eslint-loader": "2.2.1",
    "eslint-plugin-vue": "5.2.3"
  }
} 

9.显示大量数据时使用 Vue 虚拟滚动

当您需要在给定页面中显示很多行或需要循环访问大量数据时,您可能已经注意到该页面的呈现速度很快。要解决此问题,可以使用vue-virtual-scoller。

npm install vue-virtual-scroller 

它将仅渲染列表中的可见项,并重用组件和dom元素,以使其尽可能高效。它真的很容易使用,顺滑得很!

<template>
  <RecycleScroller
    class="scroller"
    :items="list"
    :item-size="32"
    key-field="id"
    v-slot="{ item }"
  >
    <div class="user">
      {{ item.name }}
    </div>
  </RecycleScroller>
</template> 

10.跟踪第三方程序包的大小

当很多人在同一个项目中工作时,如果没有人关注它们,那么已安装软件包的数量会迅速增加,令人难以置信。为了避免您的应用程序变慢(尤其是在移动网络变慢的情况下),我在Visual Studio Code中使用了导入费用包。这样,我可以从编辑器中直接看到导入的模块库有多大,并且可以查看导入的模块库过大时出了什么问题。
例如,在最近的项目中,导入了整个 lodash 库(压缩后大约24kB)。问题在于,项目里仅仅使用cloneDeep 一个方法。通过在导入费用包中识别此问题后,我们通过以下方式解决了该问题:

npm remove lodash
npm install lodash.clonedeep 

然后可以在需要的地方导入clonedeep函数:

import cloneDeep from "lodash.clonedeep"; 

为了进一步优化,您还可以使用Webpack Bundle Analyzer软件包通过交互式可缩放树状图来可视化Webpack输出文件的大小。

上一篇下一篇

猜你喜欢

热点阅读