In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the relevant knowledge of "case Analysis of Vue Code Specification". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. JS part
1. Data that is not related to rendering
The data of data in vue will be bidirectional data binding by default. If a large amount of data unrelated to rendering is directly placed in data, the performance consumed by bidirectional data binding will be wasted. The data that has nothing to do with rendering will be extracted and processed with Object.freeze.
Columns data in table can be extracted from an external js file as a configuration file, or you can define a constant to define columns data in the current .vue file, because the data that is fixed and will not be modified in any case should be wrapped with Object.freeze, which can not only improve performance but also extract the fixed data. This operation is also recommended for some data fixed at the front end of the drop-down box.
Const columnList = Object.freeze ([{title: 'name', key: 'name', align:' center'}, {title: 'gender', key: 'gender', align:' center'}])
It's important to note that Object.freeze () freezes the value, so you can still replace the reference to the variable, and make sure the data doesn't change before you use this syntax, so freezing is not appropriate if you want to modify and interact with the data.
2. Control of Modal box
A page usually has many different functions of the pop-up box, if each pop-up box sets a corresponding variable to control its display, it will lead to a relatively redundant number of variables and naming difficulties, you can use a variable to control the display of all Modal pop-up boxes on the same page.
For example, there are three Modal pop-up boxes in a page:
/ / bad / / each data controls the corresponding Modal display and hidden new Vue ({data () {return {modal1: false, modal2: false, modal3: false) }) / / good / / shows the corresponding pop-up box new Vue when modalType is the corresponding value ({data () {return {modalType:'/ / modalType value is modal1 Modal2,modal3})
3. Debounce usage
For example, remote search needs to obtain data dynamically through the interface, if every user input interface request, it is a waste of bandwidth and performance.
Multiple events will be triggered when a button is clicked multiple times, which can be combined with whether the immediate is executed immediately in the scenario:
{{item.label}}
In the process of the development of image function, the processing of pictures is often easy to be ignored, and it will also affect the efficiency of development and the performance of the page to a certain extent:
(1) the problem of image compression, unless it is specifically required that the picture must be displayed with high quality, the corresponding compression should be carried out.
(2) choose the image format for different business scenarios:
JPG is suitable for presenting colorful pictures. JPG pictures often appear as large background pictures, broadcast pictures, Banner pictures, etc.
Logo, pictures or backgrounds with simple colors and strong contrast, need transparency, etc.
Merge the commonly used and low-frequency small pictures into sprite images, and base64 the pictures that change more frequently and less than 6KB.
According to the number of pictures and the distribution of user models of the project, consider using webp to process the pictures.
4. Routing components pass parameters
The use of $route in a component makes it highly coupled to its corresponding route, thus limiting its flexibility by making the component available only on certain URL.
Use props to decouple components from routing:
(1) replace the coupling with $route
Const User = {template: 'User {{$route.params.id}}'} const router = new VueRouter ({routes: [{path:'/ user/:id', component: User}]})
(2) decoupling through props
This allows you to use the component anywhere, making it easier to reuse and test.
Const User = {props: ['id'], template:' User {{id}}'} const router = new VueRouter ({routes: [{path:'/ user/:id', component: User, props: true}, / / for routes containing named views You must add the `props` option for each named view separately: {path:'/ user/:id', components: {default: User, sidebar: Sidebar}, props: {default: true, sidebar: false}]})
Reference: routing components pass parameters
5. Vue life cycle
In parent-child components, mastering the lifecycle hook loading order of parent-child components allows developers to do the right thing at a more appropriate time.
Home import List from'. / list' export default {name: "home", components: {List}, methods: {listMounted () {console.log ('- listMounted');}}, beforeCreate () {console.log ("home beforeCreate");}, created () {console.log ("home created") }, beforeMount () {console.log ("home beforeMount");}, mounted () {console.log ("home mounted");}, beforeDestroy () {console.log ("home beforeDestroy");}, destroyed () {console.log ("home destroyed");}}
Subcomponents:
List export default {naem: "list", beforeCreate () {console.log ("list beforeCreate");}, created () {console.log ("list created");}, beforeMount () {console.log ("list beforeMount");}, mounted () {console.log ("list mounted");}, beforeDestroy () {console.log ("list beforeDestroy") }, destroyed () {console.log ("list destroyed");}}
The loading order of the parent and child components at load time:
Home beforeCreate-- > home created-- > home beforeMount-- > list created-- > list beforeMount-- > list mounted
The order in which the parent and child components are destroyed at the time of destruction:
Home beforeDestroy-- > list beforeDestroy-- > list destroyed-- > home destroyed
In the actual development process, it is encountered that the parent component is notified after a certain life cycle of the child component is completed, and then the corresponding processing is done in the parent component.
Emit up:
/ / the child component publishes the event created () {this.$emit ('done')} / / the parent component subscribes to its party in the corresponding hook
Hook:
Listen for the lifecycle of subcomponents through @ hook
6. Select optimization
As the drop-down box traverses, you need to note that the options tag remains on the same line. If there is a line break, it will result in extra white space for the selected value.
{{item.label}}
You need to keep the values of the Options and the drop-down box on the same line
{{item.label}}
7. Data data hierarchy
Data data has a data hierarchical structure, so do not overly flatten or nest too deeply. Excessive flattening will lead to data namespace conflicts, parameter transfer and processing, and too deep nesting will also lead to recursive hijacking of vue data. If the nesting level is crazy, beware of recursive stack explosion. And too deep level will lead to data operation and processing inconvenience, access to data for fault-tolerant processing is also more cumbersome. In general, it is best to keep 2-3 layers.
If there is only one layer of data, it is too flat.
{name:', age:', gender:''}
Make it inconvenient to deal with.
/ / pass ajax ({this.name, this.age, this.gender}) / / API to obtain data as interface parameters, and batch process ajax () .then (res = > {const {name, age, gender} = res.data this.name = name this.age = age this.gender = gender})
Proper hierarchical structure not only increases the maintenance and readability of the code, but also increases the convenience of operation and processing.
{person: {/ / personal information name:', age:', gender:'}}
Can operate on person
/ / pass ajax (this.person) / / interface as an interface parameter to obtain data, and batch process ajax () .then (res = > {const {name, age, gender} = res.data this.$set (this, 'person', {name, age, gender})})
8. Strategy mode
The use of policy pattern avoids too much if else judgment and can also replace the switch of simple logic.
Const formatDemandItemType = (value) = > {switch (value) {case 1: return 'basic' case 2: return 'Advanced' case 3: return 'VIP'}} / / Policy Mode const formatDemandItemType2 = (value) = > {const obj = {1:' basic', 2: 'advanced', 3: 'VIP' } return obj [value]}
Deconstruction assignment and default value, when the number of deconstruction is less than how much, it is suitable to directly deconstruct and assign default value, whether the data is aggregated or not.
Const {naem ='', age = 10, gender = 'man'} = res.data / / bad this.name = name this.age = age this.gender = gender / / good this.person = {naem, age, gender}
9. Single responsibility
At any time, a function should do one thing instead of coupling all kinds of logic together to improve the reusability and readability of a single function.
Each page will make a request for data and display it to the page when the load is complete.
Created () {this.init ();}, methods: {/ / aggregate all request actions in the init function / / split each request separately into init () {this.getList1 () this.getList2 ()}, getList1 () {/ / to do...}, getList2 () {/ / to do...}}
10. V-bind
II. HTML part
1. Html writing
When writing template templates, whether to wrap lines when there are too many attributes
two。 Physical use
When displaying some characters such as & in html, use character entities instead of
> 1 &
< 12 >1 &
< 12 三、CSS部分 1. 样式穿透 在开发中修改第三方组件样式是很常见,但由于 scoped 属性的样式隔离,可能需要去除 scoped 或是另起一个 style 。这些做法都会带来副作用(组件样式污染、不够优雅),样式穿透在css预处理器中使用才生效。 less使用 /deep/ .content /deep/ .el-button { height: 60px; } scss使用 ::v-deep .content ::v-deep .el-button { height: 60px; } stylus使用 >> >
Outer layer >. Custon-components {height: 60px;}
two。 Space
Proper spaces can improve the reading experience of the code and make it more elegant and beautiful.
After selector, attribute value:
.custom-style {/ / Selector and {spaces margin: 0; / / transform before attribute values: scale (1.5,2.2); / / add spaces after commas}
3. New line
And html type, when a line has a lot of attributes, proper line wrapping can improve reading and aesthetics
.custom-style {/ / you can define one or more attributes background: background-clip background-color background-image background-origin background-position background-repeat background-size;} in a declaration
When a rule contains multiple selectors, each selector declaration must have a unique line, which is too long, which leads to the need to scroll horizontally to read the rest of the content. The reading order should be made as vertical as possible.
.custom .header .title, .other .header .title {color: # f0f;}
4. Nesting level
When parsing css, browsers match recursively from right to left. Too deep hierarchical nesting not only affects performance, but also reduces style readability and code maintainability, which is generally controlled within 5 layers.
5. Double quotation marks
The values in the property selector must be enclosed in double quotation marks, and single quotation marks are not allowed, nor are they allowed. Double quotation marks are also recommended for attribute values in html, and single quotation marks are used in js:
.custom-style {font-family: "PingFang SC", "STHeitiSC-Light";}
6. Attribute order
When writing attributes under the same rule, they should be grouped by function. And write in the order of Formatting Model (layout, location) > Box Model (size) > Typographic (text relevance) > Visual (visual effects) to improve the readability of the code.
This is the end of "Vue Code Specification example Analysis". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.