如何通过__mocks__ 模拟封装请求
来源:6-6 路由页面的代码组织

wykun
2021-01-15
<template>
<div>
<Header @add="addUndoItem" />
<UndoList
:list="undoList"
@delete="handleItemDelete"
@status="changeStatus"
@reset="resetStatus"
@change="changeItemValue"
/>
</div>
</template>
<script>
import axios from 'axios'
import Header from './components/Header'
import UndoList from './components/UndoList'
export default {
name: 'TodoList',
components: {
Header, UndoList
},
data () {
return {
undoList: []
}
},
mounted () {
setTimeout(() => {
axios.get('/getUndoList.json').then((res) => {
this.undoList = res.data
}).catch(e => {
console.log(e)
})
}, 5000)
},
methods: {
addUndoItem (inputValue) {
this.undoList.push({
status: 'div',
value: inputValue
})
},
handleItemDelete (index) {
this.undoList.splice(index, 1)
},
changeStatus (index) {
const newList = []
this.undoList.forEach((item, itemIndex) => {
if (itemIndex === index) {
newList.push({ status: 'input', value: item.value })
} else {
newList.push({ status: 'div', value: item.value })
}
})
this.undoList = newList
},
resetStatus () {
const newList = []
this.undoList.forEach((item, itemIndex) => {
newList.push({ status: 'div', value: item.value })
})
this.undoList = newList
},
changeItemValue (obj) {
this.undoList[obj.index].value = obj.value
}
}
}
</script>
<style scoped lang="stylus">
</style>
todoList.vue 文件中使用 axios,通过__mocks__的形式我们自己实现了axios.get
但是有的场景会封装一些api方法
import ajax from './axios'
/**
* 获取
* @param { Object } params 数据参数
*/
export const getData = (params = {}) => {
return ajax.get(`/v1/authorization/page`, params)
}
然后todoList.vue 会引入这个文件去调用而不是引入aixos
import { getData } from '@/api/data'
在这种情况下.但是这种方式不能起到自实现的目的,我该如何做呢
写回答
1回答
-
Dell
2021-01-16
同学,时间有点久,这块我有点记不得了,你把 axios 的mock代码发上来,我看下告诉你怎么改
00
相似问题