preface

It has been 4 years since I contacted Vue framework, developed actual combat, and then studied source code ideas in depth. Today, we will discuss the best practices of Vue from the perspective of “coding style, performance, and security”.

Please refer to cn.vuejs.org/v2/style-gu…

Coding style

When developing code, we need to pay more attention to improving code readability. Because the same project may have more than one developer shoes in maintenance, too many holes will be teased oh ~

Here I summarize several good coding styles according to the official website combined with actual combat development:

  1. Use multiple words when naming components to avoid references to existing and future componentsHTMLElement conflict
  2. propAttribute definitions should be as detailed as possible, specifying at least the type
// Props: {status: String} props: { status: { type: String, required: true, validator: function (value) { return [ 'syncing', 'synced', 'version-conflict', 'error' ].indexOf(value) ! == -1}}}Copy the code
  1. componentdataMust be a function to prevent multiple component data from affecting each other
Export default {data () {return {foo: 'bar'}}}Copy the code
  1. usev-forBe sure to addkeyAnd avoid andv-ifWrite together
<ul v-if="shouldShowUsers"> <li v-for="user in users" :key="user.id" > {{user.name}} </li> </ul>Copy the code
  1. Set the scope for the component style
  • usescopedattribute
<template> <button class="button button-close">X</button> </template> <! <style scoped>. Button {border: none; border-radius: 2px; } .button-close { background-color: red; } </style>Copy the code
  • CSS module
<template> <button :class="[$style.button, $style.buttonClose]">X</button> </template> <! <style module>. Button {border: none; border-radius: 2px; } .buttonClose { background-color: red; } </style>Copy the code

Class names are also accessible in JavaScript:

<script> export default {created () {//  // _1mB1nfbAEqzAETAbkaBZDV_0 console.log(this.$style.button) } } </script>Copy the code
  • BEM policy: Component libraries are recommended
<template> <button class="c-Button c-Button--close">X</button> </template> <! <style>. C -Button {border: none; border-radius: 2px; } .c-Button--close { background-color: red; } </style>Copy the code
  1. privatepropertyName, useThe $_Prefix to avoid collisions
Var myGreatMixin = {//... methods: { $_myGreatMixin_update: function () { // ... }}}Copy the code

For more good coding style guides, see our website

performance

As the business code of a project grows, the project runs more expensive and builds slower, we need to consider performance optimization. From the perspective of VUE coding, we can start to optimize from the following aspects:

1. Load components as required

Lazy route loading (using import)

When the JavaScript package becomes so large that it affects page loading when the package is built, we can split the components corresponding to different routes into different code blocks and load the components when the route is accessed. Dynamic import with Import and webpack tree-shaking improves load performance by not packaging unused components to chunk.

const Home = () => import('@/components/home')
const Index = () => import('@/components/index')
const About = () => import('@/components/about')
Copy the code

2. Improve the loading speed of the first screen

Webpack volume optimization

Nowadays, most commercial front-end projects are engineering applications, such as vue/ React/Angular framework coding, webpack, construction and compilation, and slow loading of the first screen of the page, mainly due to the large volume of chunk packed to build. To improve the loading speed of the first screen, first of all, we need to optimize the volume of webpack. Please refer to the previous technical blog:

An experience doing Webpack performance optimization | Project Review

Can be modified to SSR, reduce the first screen loading time

Using SSR server rendering, components or pages can generate HTML strings through the server and then send to the browser, which can speed up the rendering loading speed of the first screen and show the document content in advance.

See: SSR- Complete guide

3. Static content that doesn’t need updating

Using the one-time interpolation function of VUE’s V-once instruction, the content of nodes that do not need to be updated can be static, which can optimize the update performance.

4. Minimize DOM hierarchy nesting

DOM rendering requires a large performance overhead, so we try to simplify the DIV structure in the development process to reduce unnecessary DOM hierarchy nesting. For components, we should minimize unnecessary component abstractions, which undoubtedly increase DOM level nesting.

5. Rendering optimization of large data volume

Long lists are loaded using virtual scrolling

The number of long lists is generally in the range of a few hundred without unexpected effects, and the browser itself can support it. But once the order of magnitude reaches thousands, the page rendering process will appear obvious lag. When the number reaches tens of thousands or even hundreds of thousands, the page may crash directly.

In order to solve the browser rendering pressure caused by long lists, a corresponding technology has emerged — virtual scrolling.

Implementation principle:

The realization of virtual scrolling is, in fact, only the list items in the visual area are loaded when the first screen is loaded. When the scrolling occurs, the list items in the visual area are obtained dynamically and the list items in the non-visual area are deleted.

For reference: “Front-end Advanced” high performance rendering of 100,000 data (virtual list)

Inactive components are available<keep-alive>The cache


is a built-in component of Vue that caches inactive component instances when wrapping dynamic components. Like
,

is an abstract component: it does not render a DOM element on its own, nor does it appear in the parent component chain.

<keep-alive> <component :is="view"></component> </keep-alive>Copy the code


is mainly used to preserve component state or avoid re-rendering.

security

XSS defenses

  • Instead of using untrusted templates to render directly, variables can be used to dynamically concatenate templates for rendering
<template>
  <div>{{ msg }}</div>
</template>
Copy the code
  • Be careful withv-html.:url.:styleEtc., avoidhtml,url,styleSuch as occursxssInjection. The data returned by the back end can be escaped and analyzed, and the unmatched data can be verifiedDOMThe label.
  • And so on…

CSRF defense

  • Token authentication
    • Step 1: Randomly generate one at the back endtokenValue, put thistokenSave tosessionIn the state; At the same time the back end put thistokenTo the front-end page;
    • Step 2: the front-end page submits requests when thetokenAdd to the request entry or header and pass it to the back end;
    • The last step: the backend validates what comes from the front endtokenwithsessionIf yes, the request is valid; otherwise, the request is illegal.
  • Referer validation

Verifying the source of the referer request is the least expensive method, but it is not 100% valid because the server does not always get the referer and there is a risk that older browsers will forge the referer.

  • Verification code

Forces the user to interact with the page application and successfully verify the captcha to complete the final request. This is a good way to contain CSRF, but the user experience is poor.

conclusion

The above mainly summarizes some practical experience of VUE development from three aspects of “coding style, performance and security”, hoping to be helpful to the development partners ~~