在一個組件里有這樣一個方法:name: 'user',
data() { const checkExist = (rule, value, callback) => { if (value) { this.$http.get(....).then(res => { if (res.id === this.itemId) {
...
}
});
}
callback();
}; return { itemId: '', rules: { name: [{ validator: checkExist, message: ‘名稱已存在’ }];
},
};
},其中這個checkExist如何提取為公共函數,可以在別的組件中直接應用。特別有一點不清楚就是函數里使用了axios的封裝this.$http,提取為公共函數后該如何處理比較科學?還有如何處理this.itemId的引用?
1 回答

飲歌長嘯
TA貢獻1951條經驗 獲得超3個贊
推薦我的這種寫法:
// utils.jsexport const checkExist = http => (rule, value, cb) => { if (value) { http() // } cb() }// 調用import { setUpcheckExit } from 'utils'const checkExist = setUpcheckExit(this.$http) ... data() { return { rules: { name: [{ validator: checkExist, message: ‘名稱已存在’ }]; } } }
添加回答
舉報
0/150
提交
取消