In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "what are the tips for building a large-scale Vue.js project", the content is easy to understand, well-organized, hope to help you solve your doubts, let the editor lead you to study and learn "what are the tips for building a large-scale Vue.js project" this article.
1. Use slot to make components more powerful and easier to understand
I recently wrote an article about Vue.js slot, which emphasizes how slot makes components easier to reuse and maintain, and why they should be used.
But what does this have to do with large Vue.js projects? A picture is usually worth a thousand words, so I'm going to paint you a picture of the first time I regret not using them.
One day, I'm going to create a popup. At first glance, there is nothing complicated, just a title, a description and some buttons. So all I do is send everything in as props. In the end, I defined three prop to customize the component, sending an event when the user clicked the button. So easy!
However, as the project evolved, the team asked us to show more new content in it: form fields, different buttons (depending on which page it is displayed on), cards, footers, and lists. I don't think it's a problem if I continue to use prop to iterate over this component. But my God, I was so wrong! The component quickly became very complex and difficult to understand because it contained countless subcomponents, used too much prop, and sent a bunch of events. I began to experience a terrible situation, when you make a little change, somewhere else on the page will collapse! I seem to have created a Frankenstein geek instead of a maintainable component!?
However, if I had relied on slot from the beginning, things would have been much better. In the end, I reconstructed everything and got this widget: easier to maintain, faster to understand, and easier to extend!
{{title}} {{description}}
Export default {props: {description: {type: String, default: null}, title: {type: String, required: true}
My view is that, from experience, projects built by developers who know when to use slot do have a big impact on their future maintainability. Because fewer events are sent, the code is easier to understand and provides more flexibility to display any component in it.
Knock on the blackboard: as a rule of thumb, when you start copying the prop of a child component in the parent component, you should consider using slot.
two。 Reasonable organization of Vuex Store
Usually, newcomers to Vue.js begin to learn about Vuex because they happen to encounter these two problems:
Access data between components that are too far apart in the component tree structure
Data needs to be persisted after the component is destroyed
At this point they will create the first Vuex store, learn the modules, and start organizing them in the application.
The problem is that there is no single pattern to follow when creating modules. However, I strongly recommend that you carefully consider how to organize them. As far as I can see, most developers prefer to organize them by functionality. For example:
Auth.
Blog.
Inbox.
Settings.
As far as I'm concerned, I find it easier to understand how to organize them according to the data model obtained from API. For example:
Users
Teams
Messages
Widgets
Articles
How you choose is up to you. The only thing to keep in mind is that a well-organized Vuex store will lead to a more efficient team in the long run. It will also make it easier for newcomers to base their ideas on your code when they join the team.
3. Use action to initiate API calls and submit data
Most, if not all, of my API calls are done in Vuex action. You might ask: why are you doing this? ?
♀️ simply says that most of the data captured by them needs to be submitted to store. In addition, they provide a layer of encapsulation and reusability, which I like to use. Some other reasons are as follows:
If I need to get the first page of the article in two places (assuming the blog page and the home page), I just need to call the appropriate dispatcher with the correct parameters. In addition to the dispatcher call, you can get the data, commit to store and return without repeating the code.
If I need to write some logic to avoid getting the first page over and over again, I can do it in one place. In addition to lightening the load on the server, this will also increase my confidence in the code.
I can track most of these Mixpanel (a site user behavior analysis tool) events, which makes the analysis code very easy to maintain. I do have some applications where all Mixpanel calls are done only in action. I don't need to know which data is being tracked, which is not, and when to send this information. The pleasure of working in this way is almost indescribable.
4. Simplify code with mapState,mapGetters,mapMutations and mapActions
Typically, you don't need to create multiple calculation properties or methods, just access state/getters or call actions/mutations within the component. Using mapState,mapGetters,mapMutations and mapActions
It can help you simplify the code, group data from store modules together, and make the code easier to understand.
/ / 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 about the above tools and methods is in the official Vuex documentation.
5. Use the API factory
I usually like to write a this.$api helper that can be called anywhere to get background API resources. There is an api folder in the root directory of my project that contains all the related classes. As follows (only partially):
Api ├── auth.js ├── notifications.js └── teams.js
Each file groups all API resources under its category. Here's how I use plug-ins to initialize this pattern in Nuxt applications (the process is similar in standard Vue applications).
/ / 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 action like this:
Export default {methods: {onSubmit () {try {this.$api.auth.login (this.email, this.password);} catch (error) {console.error (error);}}
6. Use $config to access 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 this.$config assistants, especially in templates. As always, extending the Vue object is easy:
/ / 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. Submit a name to the code according to a convention
As the project grows, you may need to browse the component history regularly. If your team does not follow the same convention to name their submissions, it will be more difficult to understand each submission.
I have always recommended using the Angular submission information guide. I follow it on every project, and in many cases, other team members will soon discover the benefits of following it.
Following these guidelines leads to more readable information, which makes it easier to track submissions when viewing project history. In short, it works like this:
Git commit-am "():" # example git commit-am "docs (changelog): update changelog to beta.5" git commit-am "fix (release): need to depend on latest rxjs and zone.js"
Take a look at their README file to learn more about it and related conventions.
8. Fix the package version after the project is launched
I know that all package should follow semantic version rules. But the reality is that some of them don't comply at all.
To avoid having to wake up in the middle of the night because a dependency destroys the entire project, locking all package versions can make your morning work less stressful.
The meaning is simple: avoid using version numbers with the ^ prefix:
{"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 Vue Virtual Scroller when displaying large amounts of data
When you need to display a large number of rows in a page, or when you need to cycle through a large amount of data, you may have noticed that the page can quickly become very slow. To solve this problem, you can use vue-virtual-scoller.
Npm install vue-virtual-scroller
It will render only the items visible in the list and reuse components and dom elements for high efficiency and good performance. It's really easy to use, silky and smooth! ✨
{{item.name}}
10. Track the size of third-party packages
When many people are working on the same project, if no one pays attention to the number of packages installed, it will soon increase. To prevent the application from slowing down (especially if the mobile network is slow), I used the import cost plug-in in VS Code. In this way, I can see from my editor how big the imported module library is, and I can check for problems when it becomes too large.
For example, in a recent project, the entire lodash library was imported (about 24kB's gzipped). As a result, only the cloneDeep method is used. By locating this problem through the import cost plug-in, we solved it as follows:
Npm remove lodashnpm install lodash.clonedeep
The cloneDeep function can be introduced where needed:
Import cloneDeep from "lodash.clonedeep"
For further optimization, you can use Webpack Bundle Analyzer to visualize the file size with interactive scalable maps.
These are all the contents of this article entitled "what are the tips for building a large Vue.js project?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.