vue中使用iview表单验证时this指针问题

需求


使用iview,在提交时对值b进行验证,使其不能大于值a

实现

    <Form
      ref="config"
      :model="config"
      :rules="configRules"
      label-position="right"
      inline
    >
      <FormItem prop="a" label="值a:" :label-width="86">
        <i-input v-model="config.a"></i-input>
      </FormItem>
      <FormItem prop="b" label="值b:" :label-width="100">
          <i-input v-model="config.b"></i-input>
      </FormItem>
      <FormItem :label-width="20">
        <Button type="primary" @click="putConfig">提交</Button>
      </FormItem>
    </Form>
export default {
  name: "Config",
  data() {
    return {
      config: {
        a: undefined,
        b: undefined
      },
      configRules: {
        b: [
          {
            trigger: "blur",
            validator(rule, value, callback) {
              console.log(this);
              if (Number(value) > Number(this.config.a)) {
                return callback(new Error("值b不能超过值a"));
              }
              return callback();
            }
          }
        ]
      }
    };
  },
}

问题以及原因

此时,validator验证函数中this.config.a根本取不到值。
通过打印this,发现此时this没有指向vue实例,
而是指向调用validator函数的对象,iview这里会用一个验证相关的对象,长这样

而这个对象中并没有config.a。
这里根本原因是普通函数中的this会指向调用时的函数作用域上,这里validator函数是被这个验证对象调用的,所以this指向了它

解决办法

将validator使用箭头函数的形式:

            validator: (rule, value, callback) => {
              console.log(this);
              if (Number(value) > Number(this.config.a)) {
                return callback(new Error("值b不能超过值a"));
              }
              return callback();
            }

箭头函数本身是没有this的,它的this是包含箭头函数的第一个普通函数中的this;
如果箭头函数没有被普通函数包含,那么它的this会指向到定义时的作用域上;
这里指向了当前vue实例,从而能够正确获取this.config.a

总结

这里通过阅读资料总结了一下关于this指向的情况:

  • 箭头函数本身是没有this的,它的this是包含箭头函数的第一个普通函数中的this;
  • 如果箭头函数没有被普通函数包含,那么它的this会指向到定义时的作用域上;
  • 而普通函数中的this会指向调用时的函数作用域上;

ps: 由于对指针理解的并不是很透彻,可能有总结不对的地方,欢迎指正~

posted @ 2019-10-28 14:40  ฅ˙-˙ฅ  阅读(823)  评论(0编辑  收藏  举报