Vue js 原代码运行正常, 模块化就报错,请指点!

问题描述:

这是vue原代码, 正常运行,
(main.js 有写
app.config.globalProperties.$http = axios
axios.defaults.baseURL = 'http://127.0.0.1:8000/'
)

methods: {
  async handleClear (id, sampleName) {
    let url = ''
    if (sampleName === '手机') { url = 'phone/' + id }
    if (sampleName === '电视) { url = 'tv/' + id }
    try {
      await this.$http.delete(url, {
        id: id,
        is_active: false
      })
    } catch (error) {
      alert('未知错误!!!!', error)
    }
  } 
},

*下面是拆成模块的, 运行就出错了

// 这是模块文件
function judgeUrl (id, sampleName) {
  let url = ''
  if (sampleName === '电视') { url = 'tv/' + id }
  if (sampleName === '手机') { url = 'phone/' + id }
  return url
}
export async function sampleDelet (id, sampleName) {
  const url = judgeUrl(id, sampleName)
  try {
    await this.$http.put(url, {                        //在这行出错---------------------------
      id: id,
      is_active: false
    })
  } catch (error) {
    alert('未知错误!!!!', error)
  }
}

这是vue 的 methods

import { sampleDelet }  from '.....'
methods:{
  handleDelete (id, sampleName) {
    sampleDelet(id, sampleName)  // 这行出错
  },
}

模块化后执行sampleDelet时,由于没有调用的对象,所以sampleDelet中this为undefined,用bind将sampleDelet中this改为vue实例就行,

handleDelete(id, sampleName) {
  sampleDelet.bind(this)(id, sampleName)  //bind修改 sampleDelet指向vue实例
}