Vue + Typescript when mounted in use on Vue given axios
In the vue
project development process, in order to facilitate the various components of the call axios
, we usually will axios mounted to the body at the entrance vue prototype file, as follows:
main.ts
import Vue from 'vue'
import axios from './utils/http'
Vue.prototype.$axios = axios;
In this case, when we request, can be used directly in the various components this.$axios
, but using the ts this.$axios
when requested, it will be given as follows:
From the figure we can see that ts not detected in Vue $ axios body. By
online access found: in the ts not recognized vue hanging below $ Axios, the prototype can not be hung on the chain. That we manually Vue prototype body mount $ axios, ts can not be identified.
Solution 1: Manually type detection told ts ignored here
Although ts can not detect Vue prototype body prototype
, but in fact we are to mount a successful, that we can be normal use, the only need to be resolved is the type of problem detected ts, so we can specify this as a any
type, so you can avoid being given problem. As follows:
(this as any).$axios
.post("/api/users/login", this.ruleForm)
.then((res: {data:any}) => {}
But using any
mean the loss of security types, and you can not get support tools.
Workaround 2: Use vue-axios
this package to deal with this issue mount
We can use vue-axios
to deal with this problem mount package. vue-axios is an extension of the axios based on plug-in Vue.prototype prototype extends the $ http attributes, it can be more convenient to use axios.
# 安装
npmi axios
npm i vue-axios -S
# 注册
Vue.use(axios,vue-axios)
# 使用
this.axios()
By using vue-axios
the package, we can directly this.axios
call.
From the above we can see that vue-axios
helped us in the Vue
mount prototype body axios
, and can be detected ts. This avoids the problem of perfect ts being given.
Explanation
Use ts development process, the error will encounter a variety of problems in the hope record, to avoid the next step on pit again, but also want to help other people.