Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the practices of establishing and maintaining large Vue.js projects

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, I would like to talk to you about the practice of establishing and maintaining large-scale Vue.js projects, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following contents for you. I hope you can gain something according to this article.

1. Use slots (slot) to make components easier to understand and more powerful

One day, I just need to create a pop-up window. At first glance, there is nothing really complicated, just including the title, description and some buttons. So all I have to do is treat everything as an attribute. Finally, I used three properties to customize the component, which emits an event when people click the button. It's very simple! : sweat_smile:

However, as the project evolved, the team asked us to display a lot of other new content: form fields, different buttons (depending on which page it is displayed on), cards, footers, and lists. I found that it seemed possible if I continued to use properties to keep the component expanding. But God,: weary: I was wrong! The component quickly became too complex to understand because it contained countless subcomponents, used too many properties, and emitted a large number of events. Volcano: I've been through a terrible situation where when you make a change somewhere, it ends up destroying everything else on another page in some way. I created a Frankenstein monster, not a maintainable component!

However, it would have been better if I had relied on slots from the start. Finally, I refactored everything to provide this widget. Easier to maintain, faster to understand and more scalable!

{{title}} {{description}}

Export default {props: {description: {type: String, default: null}, title: {type: String, required: true}

My view is that, as a rule of thumb, projects built by developers who know when to use slots do have a big impact on their future maintainability. This reduces the number of events emitted, makes the code easier to understand, and provides more flexibility when displaying any required components internally.

As a rule of thumb, remember that slots should be used from this point when eventually replicating the properties of a child component in the parent component of the child component.

two。 Organize your Vuex storage correctly

Often, new Vue.js developers start to learn Vuex because they stumble upon two problems:

They either need to access the data of a given component from another component in the tree structure that is actually too far apart, or

They need data to continue to exist after the component is destroyed.

That's when they created the first Vuex store, learned about the modules, and began to organize them in the application.

The problem is that there is no single pattern to follow when creating modules. But I strongly recommend that you consider how to organize them. As far as I know, most developers like to organize them by function. For example:

Verification code

Blog

Inbox

Setting

As far as I'm concerned, I find it easier to understand when organizing them based on the data model they extract from API. For example:

Number of users

Team

Message content

Widget

Article

Which one you choose is up to you. The only thing to keep in mind is that well-organized Vuex storage will make the team more productive in the long run. It will also make it easier for newcomers to surround your code base with your ideas when joining your team.

3. Use Vuex Actions to make API calls and submit data

Most, if not all, of my API calls are made in my Vuex operation (vuex actions). You may wonder: why is it better to call here?

Just because most of them extract the data I need to submit in vuex store. In addition, they provide the encapsulation and reusability that I really like. There are other reasons why I do this:

If I need to get the first page of the article in two different places, such as the blog and the home page, I can call the appropriate scheduler with the correct parameters. The data will be extracted, submitted, and returned, with no duplicate code except for the scheduler call.

If I need to create some logic to avoid extracting it when extracting the first page, I can do it in one place. In addition to reducing the load on the server, I am confident that it can be used anywhere.

I can track most of my Mixpanel events in these vuex actions, which makes the analysis code base really easy to maintain. I do have some applications where all Mixpanel calls are made separately in the operation. When I don't have to know what to track and when to send it, 喜悦: how happy it will be to work in this way.

Mixpanel is a data tracking and analysis company that allows developers to track a variety of user behaviors, such as the number of pages viewed by users, iPhone app analytics, Facebook app interactions, and Email analytics. Buried point analysis tools like Firebase.

4. Simplify the code base with mapState,mapGetters,mapMutations and mapAction

When you only need to access state/getter or call action/mutation within a component, you usually do not need to create multiple calculation properties or methods. Using mapState, mapGetters, mapMutations and mapActions can help you shorten your code, simplify it by grouping, and keep track of the overall situation from one place in your storage.

/ / NPMimport {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"])}}

All the information you need on these handy helpers is provided in the Vuex official documentation.

5. Use the API factory

I usually like to create a helper where this.$api can be called anywhere to get API endpoints. Under the root of the project, I have a folder where api contains all the classes (see one of the following).

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

Each node groups all endpoints of its category. This is how I initialize this pattern in a Nuxt application using a plug-in (this is very similar to the process in a standard Vue application).

/ / PROJECT: APIimport 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);}})

Now, I can simply call them in my component or Vuex operation, as follows:

Export default {methods: {onSubmit () {try {this.$api.auth.login (this.email, this.password);} catch (error) {console.error (error);}; 6. Use $config to access your environment variables (especially useful in templates)

Your project may have some global configuration variables defined in some files:

Config ├── development.json └── production.json

I like to quickly access them through the this.$config assistant, especially when I'm in a template. As always, it is easy to extend the Vue object:

/ / NPMimport Vue from "vue"; / / PROJECT: COMMONSimport 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. Follow a convention to write submission comments

As the project evolves, you will need to browse the component's submission history on a regular basis. If your team does not follow the same convention to write their submission instructions, it will be difficult to understand the behavior of each team member.

I always use and recommend Angular commit message guidelines. In every project I work on, I follow it, and in many cases, other team members quickly find it better to follow it.

Following these guidelines results in more readable messages, making it easier to track submissions when viewing project history. In short, this is how it works:

Git commit-am "():" # Here are some samplesgit commit-am "docs (changelog): update changelog to beta.5" git commit-am "fix (release): need to depend on latest rxjs and zone.js"

Check out their README files for more conventions.

8. Always freeze the version of the package when you are producing the project

I know. All software packages should follow semantic version control rules. But the reality is that some of them are not. : sweat_smile:

To avoid damaging the entire project by waking up in the middle of the night with one of your dependencies, locking the version of all packages will reduce your morning work stress. : innocent:

The meaning is simple: avoid using versions that start with ^:

{"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. Use the Vue virtual scroll bar when displaying large amounts of data

When you need to display many rows in a given page or iterate through a large amount of data, you may have noticed that the page is rendered very quickly. To solve this problem, you can use vue-virtual-scoller.

Npm install vue-virtual-scroller

It will render only the visible items in the list and reuse components and dom elements to make them as efficient as possible. It's really easy to use and smooth.

{{item.name}} 10. Track the size of third-party packages

When many people are working on the same project, the number of installed packages increases unbelievably if no one pays attention to them. To prevent your application from slowing down (especially if the mobile network slows down), I used the import fee package in Visual Studio Code. In this way, I can see directly from the editor how big the imported module library is and what goes wrong when the imported module library is too large.

For example, in a recent project, the entire lodash library was imported (about 24kB after compression). The problem is that only cloneDeep is used in the project. After identifying this issue in the import cost package, we resolved the problem in the following ways:

Npm remove lodashnpm install lodash.clonedeep

You can then import the clonedeep function where you need it:

JavaScript of import cloneDeep from "lodash.clonedeep";

For further optimization, you can also use the Webpack Bundle Analyzer package to visualize the size of the Webpack output file by interactively scaling the tree.

After reading the above, do you have any further understanding of the practice of building and maintaining large-scale Vue.js projects? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report