This approach intercepts requests within the Axios instance. It allows for a global mock toggle via environment variables and avoids sending actual HTTP requests when mocking is enabled. It is ideal for quick development where a full server is not required.
# package.json: Add a script to enable mocking via environment variable
"scripts": {
"dev": "vue-cli-service serve",
"dev:mock": "cross-env IS_MOCK=true vue-cli-service serve"
}
// vue.config.js: Inject IS_MOCK into the global scope
const IS_MOCK = process.env.IS_MOCK === 'true'
module.exports = {
chainWebpack: config => {
config.plugin('define').tap(args => {
args[0].IS_MOCK = IS_MOCK
return args
})
}
}
// mock.js: Define mock data mapped by URL
module.exports = {
'/products': {
code: 0,
data: [{ id: 001, name: 'Product 1' }],
message: 'success',
},
}
// axios-instance.js: Create axios instance with custom adapter
import axios from 'axios'
const mockMap = require('./mock.js')
var instance = axios.create({
adapter: config => {
if (mockMap[config.url] && IS_MOCK) {
return Promise.resolve({
data: mockMap[config.url],
status: 200,
})
} else {
delete config.adapter // Prevent infinite loop
return axios(config)
}
},
})
export default instance