Vue + Typescript when mounted in use on Vue given axios

Vue + Typescript when mounted in use on Vue given axios

In the vueproject 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.$axioswhen requested, it will be given as follows:

_axios.png

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 anytype, 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 anymean the loss of security types, and you can not get support tools.

Workaround 2: Use vue-axiosthis package to deal with this issue mount

We can use vue-axiosto 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-axiosthe package, we can directly this.axioscall.

vue-axios.png

From the above we can see that vue-axioshelped us in the Vuemount 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.

Guess you like

Origin www.cnblogs.com/yinhaiying/p/11314332.html