为了账号安全,请及时绑定邮箱和手机立即绑定

vue 这样的函数,怎么提取为公共函数?

vue 这样的函数,怎么提取为公共函数?

噜噜哒 2018-10-24 08:50:57
在一个组件里有这样一个方法: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: ‘名称已存在’ }];
        }
    }
}


查看完整回答
反对 回复 2018-10-24
  • 1 回答
  • 0 关注
  • 1285 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信