使用iview,在提交时对值b进行验证,使其不能大于值ahtml
<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指向了它vue
将validator使用箭头函数的形式:iview
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
ps: 因为对指针理解的并非很透彻,可能有总结不对的地方,欢迎指正~指针