需求
使用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 label="值b:" :label-width="100"> <FormItem prop="b"> <i-input v-model="config.b"></i-input> </FormItem> </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使用箭头函数的形式:
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会指向调用时的函数作用域上;