Diez minutos, te permiten aprender estas ingeniosas habilidades frías de Vue

prefacio

Llevo dos años escribiendo Vue, durante los cuales he aprendido varias técnicas para mejorar la eficiencia y el rendimiento del desarrollo, ahora resumo estas técnicas en forma de artículos.

1. Uso $attrsy$listeners

$attrsSe utiliza para registrar todos los parámetros no propscapturados y no classAND stylepasados ​​desde el componente principal al componente secundario, y $listenersse usa para registrar todos los eventos pasados ​​desde el componente principal sin .nativemodificadores. El siguiente código es un ejemplo:

Vue.component('child', {
  props: ['title'],
  template: '<h3>{{ title }}</h3>'
})

new Vue({
  data:{a:1,title:'title'},
  methods:{
    handleClick(){
      // ...
    },
    handleChange(){
      // ...
    }
  },
  template:'
    <child class="child-width" :a="a" b="1" :title="title" @click.native="handleClick" @change="handleChange">',

})
复制代码

en <child/>el

  • attrsvalor de{a:1,b:"1"}
  • listenersvalor de{change: handleChange}

Por lo general, podemos usar $attrsy $listenerscomo componente de comunicación, que es más eficiente cuando se usa en componentes de embalaje secundario, como:

Vue.component("custom-dialog", {
  // 通过v-bind="$attrs"和v-on="$listeners"把父组件传入的参数和事件都注入到el-dialog实例上
  template: '<el-dialog v-bind="$attrs" v-on="$listeners"></el-dialog>',
});

new Vue({
  data: { visible: false },
  // 这样子就可以像在el-dialog一样用visible控制custom-dialog的显示和消失
  template: '<custom-dialog :visible.sync="visible">',
});
复制代码

Otro ejemplo:

Vue.component("custom-select", {
  template: `<el-select v-bind="$attrs" v-on="$listeners">
    <el-option value="选项1" label="黄金糕"/>
    <el-option value="选项2" label="双皮奶"/>
  </el-select>`,
});

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上,相当于<el-select v-model="value">
  // 与此同时,在custom-select注入的size变量也会通过v-bind="$attrs"注入到el-select上,从而控制el-select的大小
  template: '<custom-select v-model="value" size="small">',
});
复制代码

2. Usa hábilmente$props

$porpsSe utiliza para registrar todos los argumentos propscapturados y que no sean classAND pasados ​​a los componentes secundarios desde los componentes principales . styleme gusta

Vue.component('child', {
  props: ['title'],
  template: '<h3>{{ title }}</h3>'
})

new Vue({
  data:{a:1,title:'title'},
  methods:{
    handleClick(){
      // ...
    },
    handleChange(){
      // ...
    }
  },
  template:'
    <child class="child-width" :a="a" b="1" :title="title">',

})
复制代码

Luego en <child/>, $propsel valor de {title:'title'}. $propsSe puede usar cuando los componentes propio y nieto se definen de la propsmisma manera, como por ejemplo:

Vue.component('grand-child', {
  props: ['a','b'],
  template: '<h3>{{ a + b}}</h3>'
})

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

new Vue({
  template:'
    <child class="child-width" :a="1" :b="2">',
})
复制代码

3. Uso mágico de componentes funcionales

vueLa mayor diferencia entre los componentes funcionales y los componentes generales es que no responden. No escucha ningún dato y no tiene instancia (por lo tanto, no tiene estado, lo que significa que no tiene ciclo de vida como ) created. mountedLa ventaja es que debido a que es solo una función, la sobrecarga de representación también es mucho menor.

Cambia el ejemplo del principio a un componente funcional, el código es el siguiente:

<script>
  export default {
    name: "anchor-header",
    functional: true, // 以functional:true声明该组件为函数式组件
    props: {
      level: Number,
      name: String,
      content: String,
    },
    // 对于函数式组件,render函数会额外传入一个context参数用来表示上下文,即替代this。函数式组件没有实例,故不存在this
    render: function (createElement, context) {
      const anchor = {
        props: {
          content: String,
          name: String,
        },
        template: '<a :id="name" :href="`#${name}`"> {{content}}</a>',
      };
      const anchorEl = createElement(anchor, {
        props: {
          content: context.props.content, //通过context.props调用props传入的变量
          name: context.props.name,
        },
      });
      const el = createElement(`h${context.props.level}`, [anchorEl]);
      return el;
    },
  };
</script>
复制代码

4. Uso mágico de Vue.config.devtools

De hecho, también podemos llamar vue-devtoolsa depurar en el entorno de producción, siempre que cambiemos la Vue.config.devtoolsconfiguración, como se muestra a continuación:

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

Podemos cookiedecidir si habilitar este elemento de configuración a través de la información del rol del usuario en la detección, mejorando así la conveniencia de encontrar errores en línea.

5. Uso mágico de métodos

Vue中的method可以赋值为高阶函数返回的结果,例如:

<script>
  import { debounce } from "lodash";

  export default {
    methods: {
      search: debounce(async function (keyword) {
        // ... 请求逻辑
      }, 500),
    },
  };
</script>
复制代码

上面的search函数赋值为debounce返回的结果, 也就是具有防抖功能的请求函数。这种方式可以避免我们在组件里要自己写一遍防抖逻辑。

除此之外,method还可以定义为生成器,如果我们有个函数需要执行时很强调顺序,而且需要在data里定义变量来记录上一次的状态,则可以考虑用生成器。

例如有个很常见的场景:微信的视频通话在接通的时候会显示计时器来记录通话时间,这个通话时间需要每秒更新一次,即获取通话时间的函数需要每秒执行一次,如果写成普通函数则需要在data里存放记录时间的变量。但如果用生成器则能很巧妙地解决,如下所示:

<template>
  <div id="app">
    <h3>{{ timeFormat }}</h3>
  </div>
</template>

<script>
  export default {
    name: "App",
    data() {
      return {
        // 用于显示时间的变量,是一个HH:MM:SS时间格式的字符串
        timeFormat: "",
      };
    },
    methods: {
      genTime: function* () {
        // 声明存储时、分、秒的变量
        let hour = 0;
        let minute = 0;
        let second = 0;
        while (true) {
          // 递增秒
          second += 1;
          // 如果秒到60了,则分加1,秒清零
          if (second === 60) {
            second = 0;
            minute += 1;
          }
          // 如果分到60了,则时加1,分清零
          if (minute === 60) {
            minute = 0;
            hour += 1;
          }
          // 最后返回最新的时间字符串
          yield `${hour}:${minute}:${second}`;
        }
      },
    },
    created() {
      // 通过生成器生成迭代器
      const gen = this.genTime();
      // 设置计时器定时从迭代器获取最新的时间字符串
      const timer = setInterval(() => {
        this.timeFormat = gen.next().value;
      }, 1000);
      // 在组件销毁的时候清空定时器和迭代器以免发生内存泄漏
      this.$once("hook:beforeDestroy", () => {
        clearInterval(timer);
        gen = null;
      });
    },
  };
</script>
复制代码

页面效果如下所示:

gen-method.gif

代码地址:code sandbox

但需要注意的是:method 不能是箭头函数

注意,不应该使用箭头函数来定义 method 函数 (例如 plus: () => this.a++)。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例,this.a 将是 undefined

6. 妙用 watch 的数组格式

很多开发者会在watch中某一个变量的handler里调用多个操作,如下所示:

<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的写法处理可以写成下面这种形式:

<script>
  watch:{
      'value':[
          {
              handler:function(){
                  fn1()
              },
              immediate:true
          },
          {
              handler:function(){
                  fn2()
              },
              immediate:true,
              deep:true
          }
      ]
  }
</script>
复制代码

7. 妙用$options

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

this.value = this.$options.data().value;
复制代码

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

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

<template>
  <div>
    <el-button @click="visible=!visible">打开弹窗</el-button>
    <el-dialog @open="initForm" title="个人资料" :visible.sync="visible">
      <el-form>
        <el-form-item label="名称">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio label="male"></el-radio>
            <el-radio label="female"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: "App",
  data(){
    return {
      visible: false,
      form: {
        gender: 'male',
        name: 'wayne'
      }
    }
  },
  methods:{
    initForm(){
      this.form = this.$options.data().form
    }
  }
};
</script>
复制代码

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

option_data.gif

以上代码放在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标记。标记后效果如下:

image.png

v-once

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

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

<el-select>
  <el-option
    v-for="item in options"
    v-once
    :key="item.value"
    :label="item.label"
    :value="item.value"
    >{{i}}</el-option
  >
</el-select>
复制代码

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

9. 妙用 hook 事件

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

<template>
  <child @hook:mounted="removeLoading" />
</template>
复制代码

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

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

<script>
  export default {
    created() {
      const timer = setInterval(() => {
        // 更新逻辑
      }, 1000);
      // 通过$once和hook监听实例自身的beforeDestroy,触发该生命周期时清除定时器
      this.$once("hook:beforeDestroy", () => {
        clearInterval(timer);
      });
    },
  };
</script>
复制代码

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

Supongo que te gusta

Origin juejin.im/post/7103066172530098206
Recomendado
Clasificación