Home>Article>Web Front-end> 9 Vue tips to improve development efficiency and performance

9 Vue tips to improve development efficiency and performance

青灯夜游
青灯夜游 forward
2022-06-07 11:55:44 2530browse

This article will share with you several tips that I have learned during my study ofVueto improve development efficiency and performance. I hope it will be helpful to everyone!

9 Vue tips to improve development efficiency and performance

1. Use$attrsand$listeners

## skillfully #$attrsis used to record all parameters passed from the parent component to the child component that are not captured bypropsand are notclassandstyle, but$listenersis used to record all events passed in from the parent component without the.nativemodifier. (Learning video sharing:vuejs video tutorial)

The following code is an example:

Vue.component('child', { props: ['title'], template: '

{{ title }}

' }) new Vue({ data:{a:1,title:'title'}, methods:{ handleClick(){ // ... }, handleChange(){ // ... } }, template:' ', })

is in

The value of

  • attrsis{a:1,b:"1"}
  • listenersThe value is{change: handleChange}
Usually we can use

$attrsand$listenersfor component communication. It is more efficient when used in sub-encapsulated components, such as:

Vue.component("custom-dialog", { // 通过v-bind="$attrs"和v-on="$listeners"把父组件传入的参数和事件都注入到el-dialog实例上 template: '', }); new Vue({ data: { visible: false }, // 这样子就可以像在el-dialog一样用visible控制custom-dialog的显示和消失 template: '', });
Another example:

Vue.component("custom-select", { template: `   `, }); new Vue({ data: { value: "" }, // v-model在这里其实是v-bind:value和v-on:change的组合, // 在custom-select里,通过v-bind="$attrs" v-on="$listeners"的注入, // 把父组件上的value值双向绑定到custom-select组件里的el-select上,相当于 // 与此同时,在custom-select注入的size变量也会通过v-bind="$attrs"注入到el-select上,从而控制el-select的大小 template: '', });

2. Clever use of$props

$porpsis used to record all the props passed from the parent component to the child component that are captured bypropsand are notclassandstyleparameters. For example,

Vue.component('child', { props: ['title'], template: '

{{ title }}

' }) new Vue({ data:{a:1,title:'title'}, methods:{ handleClick(){ // ... }, handleChange(){ // ... } }, template:' ', })

is in

, and the value of$propsis{title:'title'}.$propscan be used when thepropsdefined by the self component and the grandchild component are the same, such as:

Vue.component('grand-child', { props: ['a','b'], template: '

{{ a + b}}

' }) // child和grand-child都需要用到来自父组件的a与b的值时, // 在child中可以通过v-bind="$props"迅速把a与b注入到grand-child里 Vue.component('child', { props: ['a','b'], template: `
{{a}}加{{b}}的和是:
` }) new Vue({ template:' ', })

3. Use functional components

The biggest difference between functional components and general

vuecomponents is that they are non-responsive. It does not listen to any data and has no instances (so no state, meaning there is no life cycle such ascreated,mounted). The advantage is that since it is just a function, the rendering overhead is much lower.

Change the example at the beginning into a functional component, the code is as follows:

4. Use Vue.config.devtools wonderfully

In fact, we are in production You can also call

vue-devtoolsfor debugging in the environment. Just change theVue.config.devtoolsconfiguration, as shown below:

// 务必在加载 Vue 之后,立即同步设置以下内容 // 该配置项在开发版本默认为 `true`,生产版本默认为 `false` Vue.config.devtools = true;

We can pass the detection Use the user role information in

cookieto decide whether to enable this configuration item, thereby improving the convenience of online bug finding.

5. Use themethodin methods

Vueto assign the result returned by a higher-order function, for example:

The above

searchfunction is assigned the result returned bydebounce, which is the request function with anti-shake function. This method can avoid us having to write the anti-shake logic ourselves in the component.

Here is an example

sandbox. You can click on it to see the difference between themethodprocessed by the high-order function and the originalmethod. As shown below:

9 Vue tips to improve development efficiency and performance

In addition,

methodcan also be defined as agenerator, if we have a function that needs The order is emphasized during execution, and variables need to be defined indatato record the last status, then you can consider using a generator.

For example, there is a very common scenario: when a WeChat video call is connected, a timer will be displayed to record the

call time. Thiscall timerequires every second Update once, that is, the function to obtaincall timeneeds to be executed once per second. If written as a normal function, the variable recording the time needs to be stored indata. But if you use a generator, it can be solved very cleverly, as shown below:

 

The page effect is as follows:

9 Vue tips to improve development efficiency and performance

Code address: https://codesandbox.io/s/jovial-williams-nkouf?file=/src/App.vue

But it should be noted that method cannot be an arrow function

Note that arrow functions should not be used to define

methodfunctions (for example,plus: () => this.a). The reason is that arrow functions are bound to the context of the parent scope, sothiswill not point to the Vue instance as expected,this.awill beundefined.

6. Use the array format of watch wisely

Many developers will use the

handler# of a certain variable inwatch## Call multiple operations, as shown below:

<script> export default { data() { return { value: "", }; }, methods: { fn1() {}, fn2() {}, }, watch: { value: { handler() { fn1(); fn2(); }, immediate: true, deep: true, }, }, }; </script>

虽然fn1fn2都需要在value变动的时候调用,但两者的调用时机可能不同。fn1可能仅需要在deepfalse的配置下调用既可。因此,Vuewatch的值添加了Array类型来针对上面所说的情况,如果用watchArray的写法处理可以写成下面这种形式:

7. 妙用$options

$options是一个记录当前Vue组件的初始化属性选项。通常开发中,我们想把data里的某个值重置为初始化时候的值,可以像下面这么写:

this.value = this.$options.data().value;

这样子就可以在初始值由于需求需要更改时,只在data中更改即可。

这里再举一个场景:一个el-dialog中有一个el-form,我们要求每次打开el-dialog时都要重置el-form里的数据,则可以这么写:

 

每次el-dialog打开之前都会调用其@open中的方法initForm,从而重置form值到初始值。如下效果所示:

9 Vue tips to improve development efficiency and performance

以上代码放在sanbox

如果要重置data里的所有值,可以像下面这么写:

Object.assign(this.$data, this.$options.data()); // 注意千万不要写成下面的样子,这样子就更改this.$data的指向。使得其指向另外的与组件脱离的状态 this.$data = this.$options.data();

8. 妙用 v-pre,v-once

v-pre

v-pre用于跳过被标记的元素以及其子元素的编译过程,如果一个元素自身及其自元素非常打,而又不带任何与Vue相关的响应式逻辑,那么可以用v-pre标记。标记后效果如下:

9 Vue tips to improve development efficiency and performance

v-once

只渲染元素和组件一次。随后的重新渲染,元素/组件及其所有的子节点将被视为静态内容并跳过。这可以用于优化更新性能。

对于部分在首次渲染后就不会再有响应式变化的元素,可以用v-once属性去标记,如下:

 {{i}} 

如果上述例子中的变量options很大且不会再有响应式变化,那么如例子中用上v-once对性能有提升。

9. 妙用 hook 事件

如果想监听子组件的生命周期时,可以像下面例子中这么做:

这样的写法可以用于处理加载第三方的初始化过程稍漫长的子组件时,我们可以加loading动画,等到子组件加载完毕,到了mounted生命周期时,把loading动画移除。

初次之外hook还有一个常用的写法,在一个需要轮询更新数据的组件上,我们通常在created里开启定时器,然后在beforeDestroy上清除定时器。而通过hook,开启和销毁定时器的逻辑我们都可以在created里实现:

像上面这种写法就保证了逻辑的统一,遵循了单一职责原则。

(学习视频分享:web前端开发编程基础视频

The above is the detailed content of 9 Vue tips to improve development efficiency and performance. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete