使用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: 因爲對指針理解的並非很透徹,可能有總結不對的地方,歡迎指正~指針